Currently, in the process of learning TypeScript as my second language, I am encountering some challenges with arrays.
I have observed peculiar behavior when accessing the list with a variable as opposed to a hardcoded number.
The code snippet in question is:
class Game {
data: Array<Array<cell>>;
size: number;
constructor () {
this.data = [];
this.size = 20;
}
initialiseGame() {
// array of arrays full of cells created here
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 output is as expected at this point
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]) shows correct value
// this.data[randomX] returns undefined
// this.data[randomX][randomY] throws "cannot read properties of undefined" error
if (!this.data[randomX][randomY].isMine){
this.data[randomX][randomY].isMine = true;
bombsPlanted ++;
}
}
}
}
I utilized Number.isInteger()
to verify that the value is an integer and also attempted passing this.data
to plantBombs()
.
Wondering if my approach to accessing the array data
is incorrect, or if there might be a simple oversight on my part?