简体   繁体   English

遍历列表时出现 TypeError,javascript

[英]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++) {更改: for (j = 0; j < 6; i++) {
To: for (j = 0; j < 6; j++) {为: 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]声明: 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将等于: feild[6][9]并且这似乎是代码段中不在数组中的索引

Hope this helps:-)希望这可以帮助:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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