Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 toplantBombs

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading