I would expect the following code to return the result (matrix)
[ [0,0], [0,0,0,0], [0,0,0,0,0,0] ]
function zeroArray(m, n) {
let newArray = [];
let row = [];
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
row.push(0);
}
newArray.push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
but it returns: [ [0,0,0,0,0,0], [0,0,0,0,0,0], [0,0,0,0,0,0] ]
I cannot see how row is [0,0,0,0,0,0] for each iteration of the outer loop?
I see row iterating from [0,0] to [0,0,0,0] to [0,0,0,0,0,0] and pushing to newArray on each instance. However, this is evidently wrong.
Can anyone explain this result for me?
newArray.push(row)you are only pushing a reference torowso when its value changes, it changes everywhere).