JS for循环在循环之间重置为0无缘无故

时间:2017-12-14 00:51:16

标签: javascript html

我在Javascript中有以下for循环:

  for (x=0;x<newPlayer.length;x++){
    console.log(newPlayer.length,x);
    console.log("bigloopstart");
    $(".timeline-grid").append(
      "<div class='timeline-straight timeline-dashed timeline-half-left' style='grid-column-start:" + newPlayer[x].c + "; grid-row-start:" + newPlayer[x].r + `'>
        <div class='timeline-icon ` + eventDate + "'>" + iconhtml + `</div>
        <div class='timeline-team'><span>` + eventOldTeam[x] + `</span></div>
      </div>`
    );
    console.log(newPlayer.length,x);
    for (i=0,t=activeplayers.length;i<t;i++){
      if (newPlayer[x].name == activeplayers[i].name){
        activeplayers.splice(i,1);
        console.log("smallloop");
        break;
      }
    }
    console.log(newPlayer.length,x);
    console.log("bigloopend");
  }

在我测试它的情况下,newPlayer的长度为2.循环运行两次,但随后第三次运行,吐出错误,因为它无法读取数组中不存在的第三个对象的属性。

似乎由于某种原因x在第二次循环后重置为0:

enter image description here

我甚至尝试将x ++放在循环中:

  for (x=0;x<newPlayer.length;){
    console.log(newPlayer.length,x);
    console.log("bigloopstart");
    $(".timeline-grid").append(
      "<div class='timeline-straight timeline-dashed timeline-half-left' style='grid-column-start:" + newPlayer[x].c + "; grid-row-start:" + newPlayer[x].r + `'>
        <div class='timeline-icon ` + eventDate + "'>" + iconhtml + `</div>
        <div class='timeline-team'><span>` + eventOldTeam[x] + `</span></div>
      </div>`
    );
    console.log(newPlayer.length,x);
    for (i=0,t=activeplayers.length;i<t;i++){
      if (newPlayer[x].name == activeplayers[i].name){
        activeplayers.splice(i,1);
        console.log("smallloop");
        break;
      }
    }
    x++;
    console.log(newPlayer.length,x);
    console.log("bigloopend");
  }

然后控制台看起来像这样:

enter image description here

似乎第二个和第三个循环之间x被重置为0,我不明白为什么。有什么指针吗?

0 个答案:

没有答案