How to exit a loop in JavaScript: 1. Use the break statement to exit the entire loop. The code following the break statement and the following loops will not be executed. 2. Use the continue statement to exit the current loop and immediately enter the next loop. 3. Use the return statement.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
There are three ways to exit a loop in JavaScript:
Use the break statement to exit the loop
Use the continue statement to exit the loop
Use the return statement to exit the loop
Method 1: Use the break statement
The break statement will cause The running program immediately exits the innermost loop contained in it or exits a switch statement.
Since it is used to exit a loop or switch statement, this form of break statement is legal only when it appears in these statements.
If the termination conditions of a loop are very complex, it is much easier to use the break statement to implement some conditions than to use a loop expression to express all conditions.
for(var i=1;i<=10;i++) { if(i==8) { break; } document.write(i); }
When i=8, exit the for loop directly. This loop will no longer be executed!
Output result:
1234567
Method 2: Use the continue statement
The continue statement is similar to the break statement. The difference is that instead of exiting a loop, it starts a new iteration of the loop.
The continue statement can only be used in the loop body of a while statement, do/while statement, for statement, or for/in statement. Using it elsewhere will cause an error!
for(var i=1;i<=10;i++) { if(i==8) { continue; } document.write(i); }
When i=8, jump out of this for loop directly. Continue to execute next time.
Output result:
1234567910
Method 3: Use the return statement
The return statement is used to specify the value returned by the function. The return statement can only appear within the function body, appearing anywhere else in the code will cause a syntax error!
for(var i=1;i<=10;i++) { if(i==8) { return; } document.write(i); }
Output result:
Uncaught SyntaxError: Illegal return statement(…)
means illegally captured query return statement.
When the return statement is executed, function execution will stop even if there are other statements in the function body!
<script> if (username==""){ alert("请输入用户名"); return false; } if(qq==""){ alert("请输入QQ"); return false; } </script>
In the above example, when the username is empty, it will not be executed further. In some form submissions, you can also prevent the default submission method by returning false and use the Ajax submission method instead. , for example:
<form id="form" onSubmit="return false">...</form>
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to exit a loop in javascript. For more information, please follow other related articles on the PHP Chinese website!