Home > Software engineering >  Accessing data in array with variable returns undefined, whereas a hardcoded number returns the expe
Accessing data in array with variable returns undefined, whereas a hardcoded number returns the expe

Time:09-19

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 toplantBombs

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

CodePudding user response:

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