In JavaScript, use break and continue statements to jump out of a loop:
The function of the break statement is to immediately jump out of the loop, that is, to no longer execute all subsequent loops;
Instance
The code is as follows |
Copy Code |
for (i=0;i<10;i++) { if (i==3) { Break } X=x + "The number is" + i + "<br>"; } |
The function of the continue statement is to stop the executing loop and go directly to the next loop.
Instance
The code is as follows |
Copy Code |
for (i=0;i<=10;i++) { if (i==3) continue; X=x + "The number is" + i + "<br>"; } |
comparison of break and continue statements:
The code is as follows |
Copy Code |
<title> calculate the value of 1+2+3 ... +98+99+100 </title> <body> <script language= "JavaScript" type= "Text/javascript" > var total=0; for (var I=1; i++) { if (i>100) { Break } Total+=i; Continue alert (i); } Alert (total); </script> </body>
|
Save and run code, pop-up warning box, display 5050.
Analysis: After entering the loop, use the IF statement to determine the value of I, if i>100, execute the break statement, end the loop, or continue down execution. When executing to the Continue statement, the current loop is ended, the next loop is entered, and alert (i) is not executed.