I am unable to understand why we need to reinitialize the let row = []; inside the for loop to get the required result?
Please can anyone help me with this ?
Your code so far
function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes
let newArray = [];
let row = [];
for (let i = 0; i < m; i++) {
// Adds the m-th row into newArray
for (let j = 0; j < n; j++) {
// Pushes n zeroes into the current row to create the columns
row.push(0);
}
// Pushes the current row, which now has n zeroes in it, to the array
newArray.push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:67.0) Gecko/20100101 Firefox/67.0.
Thanks for your reply, please could you explain why we are getting the below array, I clearly understand what’s happening in that function, but unable to figure out why we are getting the below output.
If you put row = [] inside the loop, you are making row reference an empty array at the beginning of the iteration, then that empty array is being added elements, and then pushed to the other array.
And then at next iteration row is set again to reference an empty array…
And maybe you will ask why do all this work when we could just push trice row when it has two elements?
Well, we can’t actually, because if we want to change an element in the matrix we would change one element per row. Instead pushing three different arrays they are independent