在node.js中使用参数时,对象没有方法“减less”错误?

为什么使用这样的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中引入了使用数组方法(如reduce())。在ECMAscript5之前,甚至在所有的Javascript实现中,Array都没有reduce()。 对于像map()和reduce()这样的东西,我推荐使用像Underscore这样的库,它隐藏了实现差异。

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

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

arguments的MDN JavaScript文档包含更多信息,其中包括:

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