繁体   English   中英

使用变量访问数组中的数据返回未定义,而硬编码数字返回预期的 object

[英]Accessing data in array with variable returns undefined, whereas a hardcoded number returns the expected object

我目前正在学习 typescript 作为我的第二语言,并且对 arrays 有一些问题。
与使用硬编码数字访问列表相比,使用变量访问列表时我发现非常奇怪的行为。

我的代码如下:

class Game {
    data: Array<Array<cell>>;
    size: number;

    constructor () {
        this.data = [];
        this.size = 20;
    }

    initialiseGame() {
        // here we create an array of arrays full of cells
        this.data = []
        for (let row = 0; row < this.size; row++) {
            this.data.push([]);
            for (let col = 0; col < this.size; col++){
                this.data[row][col] = new cell(row, col);
            }
            // console.log here prints the data as I would expect
            this.plantBombs();
        }

    getRandomInt(max: number): number {
        return Math.floor(Math.random() * max)
    }

    plantBombs() {
        let randomX, randomY, bombsPlanted = 0;
        
        while (bombsPlanted < this.bombs){
            randomX = this.getRandomInt(this.size);
            randomY = this.getRandomInt(this.size);
            // console.log(this.data[0][0]) gives the expected value
            // this.data[randomX] gives undefined
            // this.data[randomX][randomY] raises the error can not read properties of undefined
            if (!this.data[randomX][randomY].isMine){
                this.data[randomX][randomY].isMine = true;
                bombsPlanted ++;
            }
        }
    }
}

我使用Number.isInteger来检查该值是否为 int,我还尝试将this.data传递给plantBombs

我访问数组data的方式是否不正确,或者我在这里错过了一些简单的事情?

你在错误的地方调用plantBombs

this.data = [];
for (let row = 0; row < this.size; row++) {
  this.data.push([]);
  for (let col = 0; col < this.size; col++) {
    this.data[row][col] = new cell(row, col);
  }
  // was there
}
// should be here
this.plantBombs();

暂无
暂无

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

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