'TypeError: Cannot set properties of undefined (setting '0')'----Array assignment

Viewed 1814

When I was solving a problem on Leetcode, I've defined an empty array. I tried push some numbers then I got this Error. I don't know why. My code here.

        // r and c are already defined numbers,arr is already defined array.
        let n = [[]]
        let index = 0
        for (let i = 0; i < r; i++) {
            for (let j = 0; j < c; j++) {
                    n[i][j] = arr[index]
                    index++;
            }
        }
        return n; 

Leetcode told me n[i][j] = arr[index] had error;

Anyone knows why? thanks.

2 Answers

Whenever the value of i becomes 1, inside the inner loop it is setting the value to n[i][j], which is n[1][0], here n[1] is undefined and it is accessing the 0th index value of undefined, that is the reason of the error.

the first iteration works fine because there is already an empty array in the 0th index (when i = 0).

here you can try doing this

let n = []
let index = 0
for (let i = 0; i < r; i++) {
    n[i] = [];
    for (let j = 0; j < c; j++) {
        n[i][j] = arr[index];
        index++;
    }
}

return n;

As the comments showed, it is possible to use .push. This is how I implemented that solution in my case.

const myArray = [[]];
const height = 7;
const width = 8;

for (let i= 0; i < height; i++) {

    if (i> 0) myArray.push([]); // this initialises the array.
    for (let j = 0; j < width; j++) {
        myArray[i][j] = "x";
    }

}

console.log(myArray)

Here is a codepen

Related