JavaScript keywords break, continue, and return

break keyword

break: Immediately jump out of the entire loop, that is, the end of the loop, and start to execute the content behind the loop (jumping directly to the curly brace
break statement will cause the running program to immediately exit the innermost loop or exit a switch statement.
Because it is used to exits a loop or switch statement, so this form of the break statement is legal only when it appears in these statements.
If a loop has a very complex termination condition, then using a break statement to achieve certain conditions is more efficient than expressing it in a loop It is much easier to express all the conditions in the formula.

for(var i=1;i<=10;i++) {
    
     
    if(i==8) {
    
     
        break; 
    } 
    document.write(i); 
} 
//当i=8的时候,直接退出for这个循环。这个循环将不再被执行!
//输出结果:1234567

continue keyword

continue: Immediately jump out of the current loop and continue to the next loop (jump to i++) 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 the while statement, do/while statement, for statement, or for/in statement, and it will cause errors if used in other places!

for(var i=1;i<=10;i++) {
    
     
    if(i==8) {
    
     
        continue; 
    } 
    document.write(i); 
} 
//当i=8的时候,直接跳出本次for循环。下次继续执行
//输出结果:1234567910

return keyword

The return statement is used to specify the value returned by the function. The return statement can only appear in the function body, and it will cause a syntax error if it appears anywhere else in the code!

for(var i=1;i<=10;i++) {
    
     
    if(i==8) {
    
     
        return; 
    } 
    document.write(i); 
} 

The execution result Uncaught SyntaxError: Illegal return statement(…)
means the illegally captured query return statement.

When the return statement is executed, function execution stops 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 downwards. 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>

Guess you like

Origin blog.csdn.net/weixin_45576567/article/details/102708094