我在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:
我甚至尝试将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");
}
然后控制台看起来像这样:
似乎第二个和第三个循环之间x
被重置为0,我不明白为什么。有什么指针吗?