I can’t figure out why different locating make different outcomes
debugging lessons
Please post your code instead of a picture of your code so that we can best help. A link to the challenge you are working on would also be helpful.
Hi, I believe you are referring to this challenge:
The row initialization before the nested for loop causes row to never reset, and since newArray.push(row)
is pushing by reference, every row in newArray becomes [0,0,0,0,0,0]
.
Reinitializing row
every time it loops in the outer for loop allows you to have a fresh row
to mutate without mutating the rows already pushed into newArray
, and you can have the correct number of 0s pushed into row
every loop, instead of row
getting longer and longer with each outer for loop.
You can see the difference by using console.log
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
row = [];
for (let j = 0; j < n; j++) {
// Pushes n zeroes into the current row to create the columns
row.push(0);
console.log('row',i+1,row);
}
// Pushes the current row, which now has n zeroes in it, to the array
newArray.push(row);
console.log('newArray',newArray,'\n');
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
You can ask for help on specific challenges by clicking Get Help → Ask For Help below Run The Tests in the challenge. This way FCC automatically links the correct challenge.
Thanks u for suggestion Sir
I’ll follow your instruction next time
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.