JavaScript提供了完全控制来处理循环和switch语句,当您想跳过一部分代码块并开始循环的下一次迭代时,可能还会出现这种情况。
为了处理所有此类情况,JavaScript提供了 break 和 continue
Break 语句
break
以下示例说明了带while循环的 break 语句的用法。请注意,一旦 x 达到5并到达紧接大括号下方的 document.write(..).)语句输出
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5) {
break; //breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
运行上面代码输出
Entering the loop
2
3
4
5
Exiting the loop!
Set the variable to different value and then try...
我们已经在 switch 语句中看到了 break
continue 语句
continue 语句告诉解释器立即开始循环的下一个迭代,并跳过剩余的代码块。当遇到 continue
此示例说明了带有while循环的 continue 语句的用法。注意当变量 x 中保存的索引达到5时,如何使用 continue
<html>
<body>
<script type = "text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10) {
x = x + 1;
if (x == 5) {
continue; //skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
运行上面代码输出
Entering the loop
2
3
4
6
7
8
9
10
Exiting the loop!
Set the variable to different value and then try...
Labels 标签语句
从JavaScript 1.2开始,标签可以与 break 和 continue 一起使用,以更精确地控制流程。 标签只是标识符,后跟一个冒号(:),该冒号用于语句或代码块。我们将看到两个不同的示例,以了解如何使用带有break和continue的标签。
以下示例显示如何使用break语句实现Label。
<html>
<body>
<script type = "text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: //This is the label name
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop:
for (var j = 0; j < 5; j++) {
if (j > 3 ) break ; //Quit the innermost loop
if (i == 2) break innerloop; //Do the same thing
if (i == 4) break outerloop; //Quit the outer loop
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
运行上面代码输出
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 2
Outerloop: 3
Innerloop: 0
Innerloop: 1
Innerloop: 2
Innerloop: 3
Outerloop: 4
Exiting the loop!
以下示例显示如何使用 continue 语句实现 Label。
<html>
<body>
<script type = "text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop: //This is the label name
for (var i = 0; i < 3; i++) {
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++) {
if (j == 3) {
continue outerloop;
}
document.write("Innerloop: " + j + "<br />");
}
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
</body>
</html>
运行上面代码输出
Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!