Home > Enterprise >  TypeError: Cannot set properties of undefined (setting '0') in Typescript
TypeError: Cannot set properties of undefined (setting '0') in Typescript

Time:03-20

I am making a minesweeper game and I want to save the mines around every field in a two-dimensional number array I tried it with this code:

let minesAround : number[][] = new Array<Array<number>>(config.fieldSize);

for (let col : number = 0; col < playingField.length; col  )
    for(let row : number = 0; row < playingField[0].length; col  ){
        minesAround[col][row] = getNumOfMinesAround(playingField, col, row);
    }

but I get an TypeError: Cannot set properties of undefined (setting '0') in Typescript Error in the line:

minesAround[col][row] = getNumOfMinesAround(playingField, col, row);

I debugged the getNumOfMinesAround methode and it works without problems and returns a number.

Edit

The inner array is not in initialized how can I initialize it?Debugging Pic

CodePudding user response:

let minesAround : number[][] = new Array<Array<number>>(config.fieldSize);

This line only helps you to create 1st dimension but 2nd dimension's values are undefined like below

"minesAround": [
    undefined,
    undefined,
    undefined,
    undefined,
    undefined
  ]

You need to add the row dimension for minesAround

let minesAround : number[][] = new Array<Array<number>>(config.fieldSize);
for (let i = 0; i < minesAround.length; i  ) {
    minesAround[i] = new Array(config.fieldSize)
}

The second problem is in your row loop

let row : number = 0; row < playingField[0].length; col  

It should be row instead of col

for (let col : number = 0; col < playingField.length; col  ) {
    for(let row : number = 0; row < playingField[0].length; row  ){
        minesAround[col][row] = getNumOfMinesAround(playingField, col, row);
    }
}
  • Related