繁体   English   中英

Typescript 方法总是返回未定义的嵌套数组

[英]Typescript method always returning undefined nested array

我正在尝试为扫雷游戏编写一个 Typescript 方法,该游戏会查看田地的邻居是否是地雷,但我每次都会遇到同样的错误:

Uncaught TypeError: Cannot read properties of undefined (reading '5')
  private getNeighbours(field: Field[][]): number[][]{
        let mineNeighbours: number[][] = new Array(field.length)
            .fill(0)
            .map(() => new Array(field.length).fill(0));

        for (let i = 0; i < field[0].length; i++){
            for (let j = 0; j < field[1].length; j++){
                for (let yOffset = -1; yOffset < 2; yOffset++){
                    for (let xOffset = -1; xOffset < 2; xOffset++){
                        if (!(i + yOffset < 0 || i + yOffset > field[0].length || j + xOffset < 0 || j + xOffset < field[1].length || xOffset == 0 || yOffset == 0)){
                            if (field[i + yOffset][j + xOffset] instanceof Mine){
                                mineNeighbours[i][j]++;
                            }
                        }
                    }
                }
            }
        }
        return mineNeighbours;
    }

错误来自我检查当前字段是否是我的实例的行

我试图调试它,以为我已经通过了一个未定义的协议,但这不是问题所在。 我的猜测是检查地雷上面的 if 语句有问题。 该方法应返回一个 int 数组,其中包含每个字段的邻居数。

您的错误将在您的 if 语句中

let validY = i + yOffset >= 0 || i + yOffset < field[0].length;
let validX = j + xOffset >= 0 || j + xOffset < field[1].length;
let isDifferentCell = xOffset !== 0 && yOffset !== 0;

if( validY && validX && isDifferentCell ) {
    if (field[i + yOffset][j + xOffset] instanceof Mine){ // Also is there a reason why this needs to be checked can the field value not be an instance of Mine? I would remove this if its always going to be a Mine
        mineNeighbours[i][j]++;
    }
}

这样可以更好地清理它,因此更容易阅读(像这样的大 if 语句会让人感到困惑)。 我相信您的问题是您分别仔细检查了每个 x 和 y。 所以有可能是无效索引,但另一个不是。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM