Home > Software engineering >  'TypeError: Cannot set properties of undefined (setting '0')'----Array assignmen
'TypeError: Cannot set properties of undefined (setting '0')'----Array assignmen

Time:04-16

When I was solving a problem on Leetcode, I've defined an empty array. I tried push some numbers then I got this Errow. 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 errow;

Anyone knows why? thanks.

CodePudding user response:

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;
  • Related