对象没有方法'在node.js中使用参数时出错
Object has no method 'reduce' error when using arguments in node.js?
为什么使用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文档有更多的信息,包括:
类数组对象,与传递给函数的实参相对应。
相关文章:
- 使用PHP和Javascript在函数内部传递alphaneumeric值作为参数时出错
- 从 javascript 获取 MVC 控制器中的操作参数时出错
- Node.js错误:参数太多上传批量数据时出错
- angularjs[ng:areq]参数'fn'不是函数,在控制台中获取字符串时出错
- WebSQL:处理SQL时出错:数量为''语句字符串中的s与参数计数不匹配
- ReactJS - 将参数传递给函数时出错
- JQuery 函数突然停止工作,转换 Javascript 参数时出错
- 资产期间出错:由于Javascript函数的默认参数而导致预编译
- 从codeehind传递javascript参数时出错
- 通过POST将参数传递到iframe中的SSRS时出错
- 将一系列数字作为参数传递给PHP中的JavaScript函数时出错
- 使用缓冲区解码base64时出错.第一个参数必须是一个数字
- toString()在使用传递参数时出错
- 提供svg v1路径参数d时出错
- JavaScript函数作为参数出错- SyntaxError:意外的token{
- 动态传递参数给javascript函数时出错
- Rails 3:向javascript函数传递参数时出错
- 对象没有方法'在node.js中使用参数时出错
- Javascript在将参数作为字符串和数字的组合传递时出错
- Angular 2在访问路由器参数时会出错