How does Javascript interpret this parameter error? -
function each(collection, callback) { if (array.isarray(collection)) { (var = 0; < collection.length; i++) { callback(collection[i]); } } else { (var prop in collection) { callback(collection[prop], prop, collection); } } } var array = [1, 2, 3, 4, 5]; function reduce(collection, callback, initial) { var current = initial; each(collection, function(current, e) { current = callback(current, e); }) return current; } console.log(reduce(array, function(a, b) { return + b }, 0)); -->>> 0
i'm trying rewrite underscore each/reduce functions, , use each function in reduce. know have mistake in there-- (current should not in each callback function) should be
each(collection, function(e) { current = callback(current, e); })
and returns 15
should, why return 0
when add current
in there parameter? shouldn't return nan
? last part of loop try add 5
, undefined nan
.
the thing add current
parameter list of callback function, have two variables - same name, in different scopes. 1 in callback shadow 1 in reduce
function.
so callback
reducer called element each
passed callback , undefined
, when assigning result (nan
) current
assign local variable of each
callback.
the outer current
variable stay unaffected, , when returned reduce
still holds initial
value initialised - 0
.
Comments
Post a Comment