Tage Danielsson
Tage Danielsson

Reputation: 51

TypeError when iterating through a list, javascript

Im making a quick little four in a row game and i've been getting an error over and over again. I have been searching around for a while now trying stuff and i still don't get why this code (sorry for bad code btw):

      var player = 0;
      var gameOver = false;
      var FinalMes = document.getElementById("gameOver");

      var feild = [
        ["_", "_", "_", "_", "_", "_", "_", "_", "_"],
        ["_", "_", "_", "_", "_", "_", "_", "_", "_"],
        ["_", "_", "_", "_", "_", "_", "_", "_", "_"],
        ["_", "_", "_", "_", "_", "_", "_", "_", "_"],
        ["_", "_", "_", "_", "_", "_", "_", "_", "_"],
        ["_", "_", "_", "_", "_", "_", "_", "_", "_"],
      ];


        for (i = 0; i < 3; i++) {
          for (j = 0; j < 6; i++) {
            if (
              feild[i][j] == 1 &&
              feild[i + 1][j + 1] == 1 &&
              feild[i + 2][j + 2] == 1 &&
              feild[i + 3][j + 3] == 1
            ) {
              f.hidden = true;
              gameOver = true;
              FinalMes.innerHTML = `Spelare ${player} vann!`;
            }
          }
        }

gives this error:

Uncaught TypeError TypeError: Cannot read properties of undefined (reading '3')

At the line:

feild[i+3][j+3] == 1

Upvotes: 0

Views: 38

Answers (1)

Sicet7
Sicet7

Reputation: 127

One issue is that your inner most loop is incrementing the same counter as the outer loop aka:
Change: for (j = 0; j < 6; i++) {
To: for (j = 0; j < 6; j++) {

Another issue is that you would read indexes that is not in the array unless the array is modified somewhere else outside of the snippet.

Lets say we're in the last iteration of the loops
the statement: feild[i+3][j+3]
would be equal to: feild[6][9] and that seems to be indexes not in the array in your snippet

Hope this helps :-)

Upvotes: 1

Related Questions