所以这段代码完美运行
var arr = [1, 2, 3, 4];
arr.forEach(function (el) {
console.log(el);
})
但如果我尝试这样做:
function printArgsInfo() {
arguments.forEach(function (el) {
console.log(el);
});
}
printArgsInfo(2, 3, 2.5, -110.5564, false);
arguments.forEach
不是函数
即使 arguments
是一个数组,如果我尝试使用 for in
循环执行此操作,它仍然有效。
最佳答案
arguments
是一个类似数组的对象,但不是数组:
var doThing = function() {
console.log(arguments.constructor.name)
console.log([].constructor.name)
}
doThing("someArgument")
将为参数
返回Object
,为空数组[]
返回Array
。
ES6 及更新版本
对于 ES6,你可以使用 rest parameters ...
,正如 torazaburo 所建议的那样。
The rest parameter syntax allows us to represent an indefinite number of arguments as an array.
function printArgsInfo(...args) {
args.forEach(el => console.log(el));
}
printArgsInfo(2, 3, 2.5, -110.5564, false);
ES5 及更早版本
对于 ES5 及更早版本,您可以借用 Array#forEach
中的方法和 call
它以 argument
作为 thisArg
。
function printArgsInfo() {
[].forEach.call(arguments, function (el) {
console.log(el);
});
}
printArgsInfo(2, 3, 2.5, -110.5564, false);
关于javascript - JS arguments.forEach 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44434622/