我试图找到一种比这种方式更好的打破嵌套循环的方法
var found = false;
for(x=0; x<10; x++){
for(i=0; i<10; i++){
if(i===3){found =true; break;}; //break inner loop
};//end of inner loop (i)
if(found){break;}; // break outer loop
};//end of outer loop for(x)
然后我找到了答案here建议使用标签来避免更多的中断和像这样的 bool 值
//var found = false; // - using labels we saved this Boolean
exitlabel:
for(x=0; x<10; x++){
for(i=0; i<10; i++){
if(i===3){break exitlabel;}; //jump to the label
};//end of inner loop (i)
//if(found){break;}; // - using labels we SAVED this if statement
};//end of outer loop for(x)
但问题是我只能在 2 个循环后 标签退出它们。当我这样做时,浏览器告诉我它找不到标签! 像这样:
for(x=0; x<10; x++){
for(i=0; i<10; i++){
if(i===3){break exitlabel;};
};
};
exitlabel: // ERROR
并在循环之前对接标签将使循环从头开始再次执行,除非我在标签之后和循环之前使用 if 语句和 bool 值来绕过 2 个循环,像这样
var found = false;
exitlabel:
if(!found){
for(x=0; x<10; x++){
for(i=0; i<10; i++){
if(i===3){found =true; break exitlabel;};
};//end of inner loop (i)
};//end of outer loop for(x)
};// end of if statement
有没有一种方法来保存 bool 值并避免将我的循环包装在这样的 IF 语句中,而只是像 C 语言一样将标签放在 2 个循环之后?
如果这是一个愚蠢的问题,请考虑我是新手,谢谢。
最佳答案
Is there a way to put a label AFTER all nested loops to break them all in one step?
通过使用 break
语句,您可以中断外部循环。它不需要之后。这使得它在您使用 break exitlable
时立即停止。
一个简单的测试表明情况确实如此。
exitlabel:
for (x = 0; x < 10; x++) {
for (i = 0; i < 10; i++) {
document.querySelector("pre").textContent += " " + i
if (i === 3) {
break exitlabel;
}
}
}
document.querySelector("pre").textContent += " after loop";
<pre></pre>
and butting the label before the loops will make the loops execute again from the beginning
那不是真的。通过使用 break
并引用附加到外部 for
语句的标签,您告诉那个 循环停止。它不会告诉它从头开始重新启动。
您所描述的听起来更像是 goto
,JavaScript 不支持它。
关于javascript - 有没有办法在所有嵌套循环之后放置一个标签以一步打破它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37115147/