Tell us what’s happening:
The code is adding 0s to the row array then pushing it to the newArray array with each loop.
The desired output is [[0,0],[0,0],[0,0]] and I understand that you either need to change the row variables scope or reset it after the 0s have been pushed to the newArray variable.
What I don’t understand is why the current erroneous code is outputting [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]] and not [[0,0],[0,0,0,0],[0,0,0,0,0,0]]. It’s adding the 0s to the new array after every loop so surely it’s adding 2 0s then 4 0s then 6 0s. Or am I missing something?
Thanks.
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 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15
.
Challenge: Use Caution When Reinitializing Variables Inside a Loop
Link to the challenge: