Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In "_reduce" function i made, spliced array is allocated to original array, but is not changed, why?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading