[Solved] Javascript multiple loop with reference


JavaScript passes arguments by reference, so whenever you pass the array to your function you pass the same instance and add it to the result array. Hence they are all the same.

An easy solution would be to build a new array inside of b and return that.

var ss = [];
var a = [{ i: 5, _r: 0 }, { i: 6, _r: 0 }, { i: 7, _r: 0 }];
var b = function (x) { 
    var result = [];
    for (var j = 0; j < x.length; j++) {
        result.push({ i : x[j].i, _r : Math.random()} );
    }
    return result; 
};
for (j = 0; j < 5; j++) { ss.push(b(a)); };
console.log(ss);

I’m not quite sure which purpose the other property serves, but you can also pass some input array and use it for the calculation. The important point is to create a new array.

9

solved Javascript multiple loop with reference