简体   繁体   中英

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

I am currently learning typescript as my second language and having some issues with arrays.
I am finding very strange behaviour when accessing the list with a variable compared to accessing the list with a hardcoded number.

My code is as follows:

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 ++;
            }
        }
    }
}

I used Number.isInteger to check that the value is an int, I also tried passing this.data to plantBombs

Is the way I am accessing the array data incorrect, or have I missed something simple here?

You are calling plantBombs in a wrong place

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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