JS arguments.forEach不是一个函数

时间:2017-06-08 11:35:50

标签: javascript foreach

所以这段代码完美无缺

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);

参数.forEach不是函数 即使是tought参数也是一个数组,如果尝试使用forin循环,它仍然有效。

3 个答案:

答案 0 :(得分:5)

arguments是一个类似于对象的数组,但不是数组。在这种情况下,您可以将Array#forEachcall方法借用argument作为thisArg



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

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




使用ES6,您可以使用rest parameters ...,因为 torazaburo 建议。

  

rest参数语法允许我们将无限数量的参数表示为数组。



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

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




答案 1 :(得分:5)

  

甚至tought参数都是一个数组

不是。



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

myFunc(1,2,3);




Arguments object是一个类似数组的对象。它不是一个数组。

答案 2 :(得分:2)

根据MDN文档:

  

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

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

因此,它不是一个真正的数组,并且不共享Array对象的原型 - 这是定义forEach方法的地方。

有趣的是,也来自MDN文档:

  

您还可以使用Array.from()方法或spread运算符将参数转换为实数数组

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);