I'm currently engaged in a learning exercise and I am attempting to comprehend the code provided. While I believed I had a solid grasp of arrays and loops, this particular piece of code has left me feeling quite puzzled.
The code snippet below:
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);
Returns
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]
However, my anticipated outcome was
[ [ 0, 0, ],
[ 0, 0, 0, 0, ],
[ 0, 0, 0, 0, 0, 0 ] ]
Based on the observation that during each iteration of i loop, we are appending (0) to row[] twice before inserting row[] into newArray.
Contrary to my expectation, upon inspection in my VSCode debugger, it appears that during each i loop, all existing indices of newArray are being updated with the most recent version of the row[] array.
What could be causing this phenomenon?