Why the code bellow generate this error:
“TypeError: Cannot read property ‘push’ of undefined” with vscode marking “newArray[i].push(row);” as the culprit
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);
}
newArray[i].push(row);
}
return newArray;
}
let matrix = zeroArray(3, 2);
console.log(matrix);
Your outer loop attempts one iteration then blows up. That one time it runs, it pushes 0 to the array rown times. Then it tries to push to the value at index 0 of newArray. There’s nothing at index 0, because newArray is []. So it blows up (push is a method that runs on an array).
Aaaalso, at the minute, you create row outside the loop, so even if you fix getting it added to newArray, all you’ll do is add more numbers: for a 3 by 2 matrix, you’ll end up with [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]] (an array containing 3 references to the same row array, which just gets more zeroes pushed to it every iteration).
Create newArray.
Every iteration of the outer loop, you need to create an empty array, so move let row = [] inside the loop.
Then on the inner loop, you push your zeroes to that row.
Then once the inner loop completes, push that now-full array to newArray.
Outer loop increments, and a new row gets created.
Then once the outer loop completes, return newArray
Aaaalso this is nitpicking, but inside the function it should be matrix not newArray; newArray is a meaningless variable name, the function returns a matrix.
So the short answer is I can’t iterate throw empty array while adding elements at the same time, my first thought was with js flexiblty I can get away with that but now I can see that I am trying to access elements that are non-existing hence the error:
Cannot read property ‘push’ of undefind.
Do you mean that you want newArray[i] to be equal to row?
If that’s the case if you use push() in that way (and if it would work, which it doesn’t) you would get newArray[i][0] equal to row. Not what you want.
If you push an array into an array, it becomes a multidimensional array, you don’t need anything more fancy than that.
Push [0,0,0,0] the first time in newArray and you get [[0,0,0,0]], push a second time, and you get [[0,0,0,0], [0,0,0,0]] etc
Every time you push an element to an array that element is added as last element of the array.
If you use newArray[i] you can use newArray[i] = [0,0,0,0]
So you do newArray[0] = [0,0,0,0]
And newArray is [[0,0,0,0]]
And then newArray[1] = [0,0,0,0]
And newArray is [[0,0,0,0],[0,0,0,0]]
Etc