在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文档包含更多信息,其中包括:
与传递给函数的参数相对应的类数组对象。
- JSON stringify与NodeJS和EJS的问题
- error handling与嵌套callbackasynchronous瀑布
- 在视图中显示passport.js身份validation错误消息
- 在AWS lambda函数中使用require
- JS正则expression式:如何从“08/08/2017”中删除前2个零
- 使用Node.js创builddynamicaudio
- (node:2157)DeprecationWarning:Mongoose:mpromise(mongoose的默认承诺库)已被弃用,请插入自己的承诺库
- 将Typescript 2.3模块发布到NPM for Angular 4 Consumption
- 在启动Meteor.js时自动加载settings.json