Object has no method 'reduce' error when using arguments in node.js?
Problem
Why do I get an error when using arguments
like this?
function sum(){
return arguments.reduce(function(a,b){
console.log(a+b)
return a+b;
},0);
}
sum(1,2,3,4);
error:
/Users/bob/Documents/Code/Node/hello.js:2
return arguments.reduce(function(a,b){
^
TypeError: Object #
This is from Mr. Crockford's JS lectures.
Problem courtesy of: doorfly
Solution
arguments
is not a real array, it's an "array-like" Object and reduce
is not a method of array-like objects. You can use reduce
by passing arguments
as context, like this:
[].reduce.call(arguments, function(a, b) {
});
Edit: more info on array-like objects here at the MDN.
Solution courtesy of: elclanrs
Discussion
View additional discussion.