我尝试使用Javascript来检查数组的位置是否有邻居,然后存储它,但我收到的错误是我不明白为什么会发生。
Uncaught TypeError: Cannot read property '-1' of undefined
at BeginGame (script.js:250)
at HTMLButtonElement.onclick ((index):41)
代码:
for(var i=0;i<gridWidth;i++){
for(var j=0;j<gridHeight;j++){
if(PuzzleMatrix[i-1][j-1]!=null){
vecinos.push(PuzzleMatrix[i-1][j-1]);
}else if(PuzzleMatrix[i][j-1]!=null){
vecinos.push(PuzzleMatrix[i][j-1]);
}else if(PuzzleMatrix[i+1][j-1]!=null){
vecinos.push(PuzzleMatrix[i+1][j-1]);
}else if(PuzzleMatrix[i-1][j]!=null){
vecinos.push(PuzzleMatrix[i-1][j]);
}else if(PuzzleMatrix[i+1][j]!=null){
vecinos.push(PuzzleMatrix[i+1][j]);
}else if(PuzzleMatrix[i-1][j+1]!=null){
vecinos.push(PuzzleMatrix[i-1][j+1]);
}else if(PuzzleMatrix[i][j+1]!=null){
vecinos.push(PuzzleMatrix[i][j+1]);
}else if(PuzzleMatrix[i+1][j+1]!=null){
vecinos.push(PuzzleMatrix[i+1][j+1]);
}
}
}