我正在尝试遍历用作游戏板的2D阵列。我需要遍历2D数组中的每个[x] [y]元素,然后查看其所有相邻单元格,并确定它们是否包含1或0。我正在制作John Conway Game of Life应用程序,需要确定有多少个“活动”(2D数组中的相邻单元格中包含1)。
当我使用嵌套的for循环迭代2D数组并尝试将当前单元格与其邻居进行比较时,遇到了未定义的错误。
for(let x = 0; x < this.state.boardHeight; x++) {
for(let y = 0; y < this.state.boardWidth; y++) {
let neighborCount = 0;
// Game of Life logic pertaining to squares being alive/dead
neighborCount += oldBoard[x - 1][y - 1];
neighborCount += oldBoard[x][y - 1];
neighborCount += oldBoard[x + 1][y - 1];
neighborCount += oldBoard[x - 1][y];
neighborCount += oldBoard[x + 1][y];
neighborCount += oldBoard[x - 1][y + 1];
neighborCount += oldBoard[x][y + 1];
neighborCount += oldBoard[x + 1][y + 1];
console.log('neighborCount ' + neighborCount[x]);
// If square has 2 live neighbors it stays alive
if(neighborCount == 2) {
newBoard[x][y] = oldBoard[x][y];
}
// If square has exactly 3 neighbors a new life square is born
else if (neighborCount == 3) {
newBoard[x][y] = 1;
}
// Is square has more than 3 live neighbors it dies
else if(neighborCount > 3){
newBoard[x][y] = 0;
}
}
}
所有neighborCount += oldBoard[x][y]
行代码均未定义返回。我如何迭代和比较有什么问题?
Cannot read property '-1' of undefined
App._this.componentDidUpdate
/src/App.js:93:43
90 | for(let y = 0; y < this.state.boardWidth; y++) {
91 | let neighborCount = 0;
92 | // Game of Life logic pertaining to squares being alive/dead
> 93 | neighborCount += oldBoard[x - 1][y - 1];
| ^
94 | neighborCount += oldBoard[x][y - 1];
95 | neighborCount += oldBoard[x + 1][y - 1];
96 | neighborCount += oldBoard[x - 1][y];
这就是我得到的错误。 Here is a Codesandbox和整个程序。
答案 0 :(得分:1)
答案在您的错误消息中:Cannot read property '-1' of undefined
您的代码从x = 0, y = 0
开始,然后第一行尝试访问oldBoard[x - 1][y - 1]
,那么这意味着什么呢?
答案:oldBoard[0 - 1][0 - 1]
,即oldBoard[-1][-1]
oldBoard[-1]
的值为undefined
,因此它实际上是在尝试做undefined[-1]
,但是undefined
没有名为-1
的属性,因此它抛出错误。
您需要以不尝试查看无效单元格的方式编写代码。