对象没有方法'在node.js中使用参数时出错

Object has no method 'reduce' error when using arguments in node.js?

本文关键字:参数 出错 js node 有方法 对象      更新时间:2023-09-26

为什么使用arguments时会出现错误?

function sum(){
    return arguments.reduce(function(a,b){
        console.log(a+b)
        return a+b;
    },0);
}
sum(1,2,3,4);
错误:

/Users/bob/Documents/Code/Node/hello.js:2
return arguments.reduce(function(a,b){
                 ^
TypeError: Object #<Object> has no method 'reduce'
    at sum (/Users/bob/Documents/Code/Node/hello.js:2:19)
    at Object.<anonymous> (/Users/bob/Documents/Code/Node/hello.js:8:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:903:3

这是Crockford先生的JS讲座

arguments不是一个真正的数组,它是一个"类数组"对象,reduce不是一个类数组对象的方法。您可以通过传递arguments作为上下文来使用reduce,如下所示:

[].reduce.call(arguments, function(a, b) {
});

编辑:更多关于类数组对象的信息在MDN。

Crockford明确指出,在ECMAscript 5中引入了对参数使用Array方法(如reduce())。在ECMAscript5之前,甚至Array都没有在所有Javascript实现中使用reduce()。对于像map()和reduce()这样的东西,我建议使用像Underscore这样的库来隐藏实现差异。

你得到一个错误,因为arguments是一个对象,而不是一个列表。考虑以下内容:

> function a(){ return arguments; }
> b = a(1, 2, 3);
> b
{ '0': 1,
  '1': 2,
  '2': 3 }

arguments的MDN JavaScript文档有更多的信息,包括:

类数组对象,与传递给函数的实参相对应。