function _each(list, iter){
for(var i=0; i<list.length; i++){
iter(list[i]);
}
}
this is code for list circuit
var slice = Array.prototype.slice;
function _rest(list, num){
return slice.call(list, num || 1);
}
I want to apply this to not only array but array-like object. So I use slice.call
function _reduce(list, iter, memo){
if(arguments.length == 2){
memo = list[0];
list = _rest(list);
}
_each(list, function(val){
memo = iter(val, memo);
})
return memo;
}
This is "_reduce" function. If I don’t put memo argument, _rest(list) is allocated to list.
var arr = [1, 2, 3, 4];
console.log(_reduce(arr, function(a, b){return a + b}));
console.log(arr);
10
test.js:79 (4) [1, 2, 3, 4]
This is result and i wonder why arr is not changed? I expect that (3) [2, 3, 4]
>Solution :
Array.prototype.slice returns a copy of the original data with the appropriate slice applied.
When you say list = _rest(list);, you’re reassigning the local variable list to the slice of everything except the first value. You’re not modifying the original array, since objects (non-primitives) are passed by reference and you’re replacing that reference with another.
If you wanted to modify the original, you would need to use Array.prototype.shift(), which removes the first element on the original array, and then you don’t need to reassign you’d just call .shift() on it.