Tell us what’s happening:
Hello, I want understand. If row is a global variable, why the result is not like this?:
[ [ 0, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]
Your code so far
I solved the problem itself, but my question is about the first output:
[ [ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0, 0 ] ]
I want to understand the behaviour of this compiler an Why this is the result and no the first.
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);
console.log(newArray);
console.log(" ");
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67
Challenge: Debugging - Use Caution When Reinitializing Variables Inside a Loop
Link to the challenge: