[英]"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') " .在尝试向我拥有的数组添加新元素时,我收到错误“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 :如果您运行此代码片段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:控制台 output 是:
[[[[]]], [], []] // 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.如果使用arry[turn][i1][i2]
,则必须覆盖(预先初始化)所有可能的turn
和i1
值以避免错误。 Or, even better, to change the approach/algorithm completely.或者,更好的是,完全改变方法/算法。 Find cleaner way.寻找更清洁的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.