- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用名为“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/
我正在使用名为“P5.js”的 JavaScript 库。它有一个 setup 函数,当一切都加载完毕时执行,还有一个 draw 函数,它在 setup() 执行后开始循环。 我正在尝试编写一个迷宫生
我是一名优秀的程序员,十分优秀!