简体   繁体   中英

"Uncaught TypeError: Cannot set properties of undefined" on Javascript

While trying to add new elements to the array I have, I get the error "Uncaught TypeError: Cannot set properties of undefined (setting '1') " .

var arry = [[[[]]]],
    i1 = 0,
    i2 = 0,
    intervalRate = 1000;
    turn = 0, a = 10, b = 5;

for(i = 0; i < 2; i++) arry.push([]);

    setInterval(() => {
        
        
        arry[turn][i1][i2] = ([a, b]); //the error comes in this line
        i2++;
        if(i2 % 5 == 0 && i2 != 0){
            i1++;
            i2 = 0;
            arry.push([]);
        } 

        turn++;
        if(turn == 3) turn = 0;

        a += 5; b += 5;

    }, intervalRate);

How can I solve this?

If you run this code snippet JSFiddle :

var arry = [[[[]]]],
    i1 = 0,
    i2 = 0,
    intervalRate = 1000;
    turn = 0, a = 10, b = 5;

for(i = 0; i < 2; i++) arry.push([]);

console.log(arry);
console.log(arry[0][0]);
console.log(arry[1][0]);

Console output is:

[[[[]]], [], []] // 3 root elements
[[]] // 1st child of array[0];
undefined // 1st child of array[1]

So to fix, you would have to initialize all elements of all array dimensions, but the last one. If you use arry[turn][i1][i2] , you have to cover (initialize upfront) for all possible values of turn and i1 to avoid error. Or, even better, to change the approach/algorithm completely. Find cleaner way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM