Firstly, sorry for the not specific title. I don't know how to call this.
Ok, here goes my question.
I am going to take Javascript's reduce function here.
I know the "reduce" function is defined as follows
function reduce(array, combine, start) {
var current = start;
for (var i = 0; i < array.length; i++)
current = combine(current, array[i]);
return current;
}
Well, what I don't understand is this.
Why
[1, 2, 3, 4].reduce(function(a, b) {
return a + b;
}, 0);
and
reduce([1, 2, 3, 4], function(a, b) {
return a + b;
}, 0);
returns the same result of "10"?
I know how the function works. I just don't understand why
xx.functionABC(param2,param3)
is the same as
functionABC(param1,param2,param3)
Thanks for the reply everyone!
Thanks for all the comments and answers!
I feel stupid for not checking with other methods first (or shouldn't try with a built in function).
2 Answers 2
The first code snippet is using Array.prototype.reduce, and the second snippet is using your custom reduce function.
They happen to be implemented mostly the same, and therefore give the same result.
Here is an example of how they are different. Array.prototype.reduce passes additional arguments to the combine callback, namely the current array index, and a reference to the array itself. Your function does not pass these arguments.
function reduce(array, combine, start) {
var current = start;
for (var i = 0; i < array.length; i++)
current = combine(current, array[i]);
return current;
}
function foo(a, b, i) { return a + b * i; };
console.log([1, 2, 3, 4].reduce(foo, 0));
console.log(reduce([1, 2, 3, 4], foo, 0));
(See the developer console of your browser for the result.)
2 Comments
value = callback(value, t[k], k, t);There is has a method Array.prototype.reduce() in js. It means method belongs to the Array.prototype. But there is no simple function reduce(). Probably you use the some library provide it.
array.reduceis a built-in function for Arrays.reducefunction is also part of thearray's prototype. It was just coincidence that both work.