javascript - 无法使用循环中的参数字符填充数组

标签 javascript arrays loops arguments

function arrayAnalyzer(numbers){ 
var array = []; 
  for(var i = 0; i < arguments.length; i++) { 
    array.push(arguments.charAt(i)); 
  }
  console.log(array); 
} 

arrayAnalyzer(7, -3, 0, 12, 44, -5, 3);

它给我的“arguments.charAt”无效

最佳答案

只需推送参数[i]:

function arrayAnalyzer(numbers) {
  var array = []; 
  for(var i = 0; i < arguments.length; i++) { 
    array.push(arguments[i]); 
  }
  console.log(array); 
} 

arrayAnalyzer(7, -3, 0, 12, 44, -5, 3);

您也可以用更短的方式做同样的事情:

function arrayAnalyzer(numbers) {
  // Since arguments is Array-like object let's convert it to array:
  return Array.prototype.slice.call(arguments);
} 

console.log(arrayAnalyzer(7, -3, 0, 12, 44, -5, 3));

顺便说一句,charAtmethod of String prototypeargumentsArray-like object当然不是字符串。

关于javascript - 无法使用循环中的参数字符填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31493785/

相关文章:

PHP随机匹配一个数组到自身

C++控制台游戏,故障重新切换语句以在二维数组中移动字符

c - 为什么我在运行代码时收到调试断言失败错误

javascript - html 中不存在的资源是否会减慢页面呈现速度?

javascript - 将数组转换为对象

javascript - 显式初始化 Jquery Mobile?

javascript - 组件中缺少历史记录

arrays - 在 SnapLogic 中将数组转换为字符串

c - 程序拒绝进入for循环

python - 循环遍历 python 字典并操作每个值