简体   繁体   中英

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

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:-)

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