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/>"); } </script> </body> </html>