Javascript 对象没有方法';减少';在node.js中使用参数时出错?
为什么这样使用Javascript 对象没有方法';减少';在node.js中使用参数时出错?,javascript,node.js,Javascript,Node.js,为什么这样使用参数时会出错 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){ ^
参数时会出错
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
/Users/bob/Documents/code/Node/hello.js:2
返回参数.reduce(函数(a,b){
^
TypeError:对象#没有方法“reduce”
总计(/Users/bob/Documents/Code/Node/hello.js:2:19)
at Object..arguments
不是一个真正的数组,它是一个“类似数组”的对象,reduce
不是类似数组的对象的方法。您可以通过将arguments
作为上下文传递来使用reduce
,如下所示:
[].reduce.call(arguments, function(a, b) {
});
<强>编辑:在.
中的数组类对象的更多信息,您会得到一个错误,因为<代码>参数是一个对象而不是一个列表。请考虑以下内容:
> function a(){ return arguments; }
> b = a(1, 2, 3);
> b
{ '0': 1,
'1': 2,
'2': 3 }
的MDN JavaScript文档包含更多信息,包括:
与传递给函数的参数相对应的类似数组的对象
Crockford明确指出,在ECMAscript 5中引入了对参数使用诸如reduce()之类的数组方法。在ECMAscript 5之前,在所有Javascript实现中,甚至连数组都没有reduce()。对于map()和reduce()之类的东西,我建议使用类似于库的下划线来隐藏实现差异。数组和“类似数组”之间的区别是什么对象?@AndersonGreen One从Array
继承了它的原型,包括像reduce
这样的好东西。其他的没有,但仍然有数字索引,这使它们类似于数组。@AndersonGreen:检查我的编辑,在MDN中有一些有用的信息,滚动直到找到“Array-like”标题。这个功能:函数sum(){return[].reduce.call(参数,函数(a,b){console.log(a+b)return a+b;},0);}sum(1,2,3,4);
@elclanrs-谢谢!不知道Crockford先生为什么没有在他的讲座中给出一个工作示例?