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

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

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.

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

Edit

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

>Solution :

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