简体   繁体   中英

Getting TypeError Cannot read property '0' of undefined when variable is defined

I have an array called game.

var game = [
[0,0,0,0,0],
[0,0,0,0,0],
[0,1,1,1,0],
[0,0,0,0,0],
[0,0,0,0,0]
]

During this loop (x, y, and after are created early in the code)

y = 0
x = 0
while (x <= 3){
while (y <= 3) {
    if (game[x+1][y+1] == 1 && game[x][y] + game[x][y+1] + game[x][y+2] + game[x+1][y] + game[x+1][y+2] + game[x+2][y] + game[x+2][y+1] + game[x+2][y+2] <= 1 || game[x][y] + game[x][y+1] + game[x][y+2] + game[x+1][y] + game[x+1][y+2] + game[x+2][y] + game[x+2][y+1] + game[x+2][y+2] >= 4) {
        after[x][y] = 0
    }
    if (game[x+1][y+1] == 0 && game[x][y] + game[x][y+1] + game[x][y+2] + game[x+1][y] + game[x+1][y+2] + game[x+2][y] + game[x+2][y+1] + game[x+2][y+2] == 3) {
        after[x][y] = 1
    }
    y++
}
y = 0
x++
}

When run, it will give me a TypeError: Cannot read property '0' of undefined to random points. Such as game[x+2][y].

In the While statement, I would have to change it to 2 because it is going through 0-2 which is the 3x3 grid I want, while previous it was going through a 4x4 grid because it was going through 0-3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM