描述JavaScript Break,Continue和Label语句
break语句
break语句用于提早退出循环,使之脱离封闭的花括号。break语句退出循环。
让我们来看一个JavaScript中的break语句示例。以下示例说明了带有while循环的break语句的用法。请注意,一旦x达到5并到达紧接大括号下方的document.write(..)语句,循环将如何提前中断
示例
<html> <body> <script> 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> </body> </html>
Continue语句
Continue语句告诉解释器立即开始循环的下一个迭代,并跳过剩余的代码块。当遇到continue语句时,程序流立即移至循环检查表达式,如果条件仍然为真,则它将开始下一次迭代,否则,控件退出循环。
Continue语句在循环中进行了一次迭代。此示例说明了带有while循环的continue语句的用法。请注意,当变量x中的索引达到8时,如何使用continue语句跳过打印
示例
<html> <body> <script> var x = 1; document.write("Entering the loop<br /> "); while (x < 10) { x = x + 1; if (x == 8) { continue; // skip rest of the loop body } document.write( x + "<br />"); } document.write("Exiting the loop!<br /> "); </script> </body> </html>
标签语句
JavaScript标签语句用于在标签之前添加标识符。标签可以与break和continue语句一起使用,以更精确地控制流程。标签只是标识符,后跟一个冒号(:),该冒号应用于语句或代码块。我们将看到两个不同的示例,以了解如何使用带有break和continue的标签。
您可以尝试使用break语句运行以下代码以使用标签来控制流程
示例
<html> <body> <script> document.write("Entering the loop!<br /> "); outerloop: //这是标签名称 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>