JavaScript Break and Continue statements

JavaScript break ends the loop

The JavaScript break command means to end the current loop and then continue executing the code after the loop. break is generally used with if conditional statements, as shown in the following example:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
    <script type="text/javascript">
        var i=1
        for (i = 1; i<=10; i++) {
        if (i > 5) {
        break;
        }
        document.write(i + "<br />");
        }
    </script>
</head>
<body>
</body>
</html>

Running result:

1
2
3
4
5

JavaScript continue skips the current loop

Different from the break command, JavaScript continue skips the current loop (equivalent to is invalid in this cycle) and continue to the next cycle until the end of the cycle.

The following example demonstrates the output of odd numbers between 1-10:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
    <script type="text/javascript">
        var i=1
        for (i = 1; i<=10; i++) {
        if ( i % 2 == 0 ){
        continue;
        }
        document.write(i + "<br />");
        }
    </script>
</head>
<body>
</body>
</html>

Running result:

1
3
5
7
9

Tips

As shown in the above example, whether it is break to end the loop or continue to jump After passing the current loop, you need to pay attention to the location where the break/continue command is executed. In the above example of outputting odd numbers, if the continue command is placed after the document.write command, the result of outputting odd numbers cannot be achieved.

JavaScript Tags

As you saw in the chapter on switch statements, JavaScript statements can be tagged.

To label a JavaScript statement, add a colon before the statement:

label:
statements

The break and continue statements are just Statements that can jump out of code blocks.

Syntax:

break labelname;

continue labelname;

continue statement (with or without label reference) only Can be used in loops.

break statement (without label reference), can only be used in a loop or switch.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<body>
<script>
cars=["BMW","Volvo","Saab","Ford"];
list:{
document.write(cars[0] + "<br>"); 
document.write(cars[1] + "<br>"); 
document.write(cars[2] + "<br>"); 
break list;
document.write(cars[3] + "<br>"); 
document.write(cars[4] + "<br>"); 
document.write(cars[5] + "<br>"); 
}
</script>
</body>
</html>


Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var i=1 for (i = 1; i<=10; i++) { if ( i % 2 == 0 ){ continue; } document.write(i + "<br />"); } </script> </head> <body> </body> </html>
submitReset Code