![](/img/trans.png)
[英]JavaScript Uncaught TypeError: Cannot set property '-1' of undefined
[英]"Uncaught TypeError: Cannot set properties of undefined" on Javascript
在嘗試向我擁有的數組添加新元素時,我收到錯誤“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);
我該如何解決這個問題?
如果您運行此代碼片段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]);
控制台 output 是:
[[[[]]], [], []] // 3 root elements
[[]] // 1st child of array[0];
undefined // 1st child of array[1]
所以要修復,你必須初始化所有數組維度的所有元素,但最后一個。 如果使用arry[turn][i1][i2]
,則必須覆蓋(預先初始化)所有可能的turn
和i1
值以避免錯誤。 或者,更好的是,完全改變方法/算法。 尋找更清潔的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.