在矩阵中寻找邻居并存储它

时间:2018-06-06 21:05:44

标签: javascript neighbours

我尝试使用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]);
                }
          }
      }

0 个答案:

没有答案