JS arguments.forEach不是一个函数。

11

所以这段代码完美运作。

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,它几乎已经过时了。 - user663031
Array.prototype.slice.call(arguments).forEach... 替换 arguments.forEach... - Seraf
3个回答

18

arguments是一个类似数组的对象,但不是一个真正的数组:

var doThing = function() {
    console.log(arguments.constructor.name)
    console.log([].constructor.name)
}

doThing("someArgument")



将返回Object作为arguments,将返回Array作为空数组[]

ES6及更高版本

在ES6中,您可以像torazaburo建议的那样使用剩余参数...

剩余参数语法允许我们将不确定数量的参数表示为数组。

function printArgsInfo(...args) {
    args.forEach(el => console.log(el));
}

printArgsInfo(2, 3, 2.5, -110.5564, false);

ES5及以下版本

对于ES5及以下版本,你可以借用Array#forEach的方法,并使用thisArg作为argumentcall它。

function printArgsInfo() {
    [].forEach.call(arguments, function (el) {
        console.log(el);
    });
}

printArgsInfo(2, 3, 2.5, -110.5564, false);


3
我很惊讶你没有建议显而易见的 [...arguments].forEach。或者更好的办法是,只需使用 function printArgsInfo(...args) - user663031
1
@torazaburo,没错,我也加上了,感谢你的提示。 - Nina Scholz

7
根据MDN文档:

参数对象是一个类似于数组的对象,对应于传递给函数的参数。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

所以,它不是真正的数组,也不共享Array对象的原型--这是forEach方法定义的地方。
有趣的是,还从MDN文档中得知:
您还可以使用Array.from()方法或展开运算符将参数转换为真正的数组。
var args = Array.from(arguments);

所以,这是一个带有您的代码的工作示例:

function printArgsInfo() {
    var args = Array.from(arguments);

    args.forEach(function (el) {
        console.log(el);
    });
}

printArgsInfo(2, 3, 2.5, -110.5564, false);

https://davidwalsh.name/arguments-array 这篇文章确实讲解了参数数组,但是有些地方可以更好地解释。 - Все Едно

4

尽管arguments看起来像一个数组

但事实上它并不是数组。

function myFunc() {
    console.log(arguments instanceof Array);
}

myFunc(1,2,3);

参数对象是一个类似数组的对象,但它不是一个真正的数组。


也许您还可以查看https://dev59.com/NnNA5IYBdhLWcg3wcNbF - Chris Lear
console.log(typeof arguments); 是的,它显示它是一个对象,而且似乎很合理不能对其进行 foreach,从来没有想过它不是一个数组。 - Все Едно
console.log(typeof []) — 数组是对象(但不是所有对象都是数组)。 - Quentin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接