簡體   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