break语句用于提早退出循环,使之脱离封闭的花括号。break语句退出循环。
让我们看一个不使用label的JavaScript中的break语句示例-
<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>
标签用于控制程序的流程,也就是说,在嵌套的for循环中使用它来跳转到内部或外部循环。您可以尝试使用break语句运行以下代码以使用标签来控制流程-
<html> <body> <script> 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>