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

Viewed 26

I have a matrix 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 this error:

TypeError: Cannot read property '0' of undefined to random points. Such as game[x+2][y].

1 Answers

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.

Related