Tell us what’s happening:
Hi All,
I understand the model answer but i just want to understand why this output is caused simply because row array isn’t resetting(global variable).
From my understanding, the first iteration of outer loop will end after inner loop runs twice, row is pushed to newArray, then outer loop begins to start second iteration. So my question is why does the extra columns come from? How does the loop know when to start a new row?
[
[0][0] <—first iteration of outer loop
[0][0] <—second iteration of outer loop
[0][0] <–third iteration of outer loop
]
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 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop