gpt4 book ai didi

javascript - 未捕获的类型错误 : Cannot read property of undefined when trying to receive an object scecific variable form a 2D array

转载 作者:行者123 更新时间:2023-11-29 23:51:36 25 4
gpt4 key购买 nike

我正在使用名为“P5.js”的 JavaScript 库。它有一个 setup 函数,当一切都加载完毕时执行,还有一个 draw 函数,它在 setup() 执行后开始循环。

我正在尝试编写一个迷宫生成算法,我正在为名为 x 的网格使用多维数组(数组的数组),它只包含 Cell 对象。

我正在创建这样的数组:

//Global variable declaration
var x = [];

//What I write in setup()
for(var i = 0; i < nw; i++) {
var y = [];
x.push(y);
}

for(var i = 0; i < nw; i++) {
for(var j = 0; j < nh; j++) {
var c = new Cell(i, j);
x[i].push(c);
}
}

draw() 循环中,我使用一个也称为 draw() 的函数显示单元格,如下所示:

for(var i = 0; i < x.length; i++) {
for(var j = 0; j < nh; j++) {
x[i][j].draw();
x[i][j].checkNeighbours();
}
}

draw() 函数在单元格的每一侧绘制一条线。

现在我的问题来了:

我有一个名为 checkNeighbours() 的函数,它想像这样从 Cell 对象访问多维数组:

this.checkNeighbours = function() {
if(this.indexY == 0 || x[this.indexX][this.indexY - 1].visited) {
this.neighbours[0] = false;
}
}

现在我的浏览器在说(在控制台中)之前只绘制前两个单元格(x[0][0]x[0][1]) : “未捕获的类型错误:无法读取未定义的属性‘0’”

问题不是可能的越界异常(在 java 中调用),因为当我删除 - 1 时它也确实说了同样的话。当我输入 x[0][0].visited 时,它返回 false 而不是 undefined。有谁知道导致此问题的原因吗?

最佳答案

这不是说“无法设置未定义的属性 0”,所以它不可能是 this.neighbors[0] = false 行。

x[this.indexX] 必须未定义。

试试这个:

this.checkNeighbours = function() {

console.log('this.indexX: ', this.indexX);
var xx = x[this.indexX];
console.log('xx: ', xx);

if(this.indexY == 0 || x[this.indexX][this.indexY - 1].visited) {
this.neighbours[0] = false;
}
}

另外,在设置之后,在第一次调用 checkNeighbours 之前,只是 console.log(x) 本身,并在控制台中检查它,看看它是否包含您期望的内容。

另一种可能是错误根本不在这段代码中,而是在 Cell 构造函数中或其他地方。

错误引用了哪一行代码?

关于javascript - 未捕获的类型错误 : Cannot read property of undefined when trying to receive an object scecific variable form a 2D array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42682661/

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