gpt4 book ai didi

javascript - 无法在二维数组中设置未定义的属性 '3'

转载 作者:行者123 更新时间:2023-11-28 21:05:16 25 4
gpt4 key购买 nike

我正在尝试创建一个二维数组,但收到此错误。

我循环一个对象并尝试分配它们,但它不允许我为第二个维度分配值。

这就是我所拥有的:

//this is globally set
var gcollision = new Array();

function create() {
for (var X in sdata) {
X = parseInt(X);
for (var Y in sdata[X]) {
Y = parseInt(Y);
width = parseInt(sdata[X][Y][2]);
height = parseInt(sdata[X][Y][3]);
for (i = X; i != X + width; i++) {
//error occurs here "Uncaught TypeError: Cannot set property '3' of undefined"
gcollision[i][Y] = 1
for (j = Y; j != Y + height; j++) {
gcollision[X][j] = 1
}
}
}
}

如何让它正确设置 的值?

编辑 sdata 如下所示:

var sdata = {"4":{"7":["1","7","3","3"]},"3":{"3":["2","8","1","1"]}};

最佳答案

//this is globally set
var gcollision = new Array();

function create(){
for (var X in sdata) {
X = parseInt(X);
for (var Y in sdata[X]) {
Y = parseInt(Y);
width = parseInt(sdata[X][Y][2]);
height = parseInt(sdata[X][Y][3]);

for (i=X; i!= X+width; i++) {
if( typeof gcollision[i] == 'undefined' ) gcollision[i] = new Array();
gcollision[i][Y] = 1

for (j=Y; j!=Y+height; j++) {
if( typeof gcollision[X] == 'undefined' ) gcollision[X] = new Array();
gcollision[X][j] = 1
}
}
}
}

基本上,即使您创建了数组,这些索引还不存在,因此在定义它们之前,您不能将它们作为数组引用。

如果您将 for 循环设置得更优化,则不必执行 isset,只需在内循环之前创建 gcol[index] = Array();第一次访问它的位置。

关于javascript - 无法在二维数组中设置未定义的属性 '3',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10047495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com