The problems come from the challenge Debugging: Use Caution When Reinitializing Variables Inside a Loop
The challenge itself is easy. You need to reinitialize the array “row” when “i” increased. But the wrong result is confusing:
I thought it would be [[0,0],[0,0,0,0],[0,0,0,0,0,0]].
I changed code to this:
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);
}
console.log("the row is",row);
console.log("the rowlength is",row.length);
console.log("the newArray before push is",newArray);
console.log("the newArraylength is",newArray.length);
console.log("\n");
newArray.push(row);
console.log("the newArray after push is",newArray);
console.log("the newArraylength is",newArray.length);
console.log("\nnext loop\n\n")
}
}
let matrix = zeroArray(3, 2);
The result is:
When I expand arrays, “row” and “newArray” are strange. There are two differernt length of “row” and “newArray” . I expand arrays in first loop like this:
Beside of the length, it looks like that the newArray has already been pushed zeros in other rows during first loop, even before the code executed.