和C语言一样,JavaScript中可以通过break语句终止循环的继续执行
<!DOCTYPE html> <html> <body> <p>75271.com Click the button to do a loop with a break.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var x="",i=0; for (i=0;i<10;i++) { if (i==3) { break; } x=x + "The number is " + i + "<br>"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html>
上面的代码输出
The number is 0 The number is 1 The number is 2