Home > Article > Web Front-end > javaScript break and continue statements
This article shares with you the code of break and continue statements in JavaScript. It is very detailed and practical. It is suitable for beginners of JavaScript. Friends who need it can refer to it.
Both the break statement and the continue statement have a jump function, which allows the code to be executed out of the existing order.
The break statement is used to break out of the loop.
var i = 0; while (i < 100) { console.log(i); i++; if (i === 10) break; } // 控制台输出结果为:0 1 2 3 4 5 6 7 8 9
The above code will only execute the loop 10 times. Once i
is equal to 10, it will jump out of the loop.
for
Loops can also use the break
statement to break out of the loop.
for (var i = 0; i < 5; i++) { console.log(i); if (i === 3) break; } // 0 // 1 // 2 // 3
The above code is executed until i
is equal to 3, and the loop will be jumped out. The
continue
statement is used to immediately terminate this cycle, return to the head of the loop structure, and start the next cycle.
var i = 0; while (i < 10){ i++; if (i % 2 === 0) continue; console.log('i 当前为:' + i); } // 控制台输出结果为: 1 3 5 7 9
The above code will output the value of i
only when i
is an odd number. If i
is an even number, enter the next cycle directly.
JavaScript language allows, there is a label in front of the statement, which is equivalent to a locator and is used to jump to any position in the program. The format of the label is as follows .
Syntax:
label:statement
The tag can be any identifier, but cannot be Reserved words, the statement part can be any statement.
标签通常与break
语句和continue
语句配合使用,跳出特定的循环。
top: for (var i = 0; i < 3; i++){ for (var j = 0; j < 3; j++){ if (i === 1 && j === 1) break top; console.log('i=' + i + ', j=' + j); } } // i=0, j=0 // i=0, j=1 // i=0, j=2 // i=1, j=0
上面代码为一个双重循环区块,break
命令后面加上了top
标签(注意,top
不用加引号),满足条件时,直接跳出双层循环。
continue
语句也可以与标签配合使用。
top: for (var i = 0; i < 3; i++){ for (var j = 0; j < 3; j++){ if (i === 1 && j === 1) continue top; console.log('i=' + i + ', j=' + j); } } // i=0, j=0 // i=0, j=1 // i=0, j=2 // i=1, j=0 // i=2, j=0 // i=2, j=1 // i=2, j=2
上面代码中,continue
命令后面有一个标签名,满足条件时,会跳过当前循环,直接进入下一轮外层循环。
请注意:如果存在多重循环,不带参数的break
语句和continue
语句都只针对最内层循环。
如果break语句后面不使用标签,则会跳出当前内层循环进入外层循环的下一轮。
for (var i = 0; i < 3; i++){ for (var j = 0; j < 3; j++){ if (i === 1 && j === 1) break; console.log('i=' + i + ', j=' + j); } } // i=0, j=0 // i=0, j=1 // i=0, j=2 // i=1, j=0 // i=2, j=0 // i=2, j=1 // i=2, j=2
如果continue
语句后面不使用标签,则只能进入下一轮的内层循环。
for (var i = 0; i < 3; i++){ for (var j = 0; j < 3; j++){ if (i === 1 && j === 1) continue; console.log('i=' + i + ', j=' + j); } } // i=0, j=0 // i=0, j=1 // i=0, j=2 // i=1, j=0 // i=1, j=2 // i=2, j=0 // i=2, j=1 // i=2, j=2
The above is the detailed content of javaScript break and continue statements. For more information, please follow other related articles on the PHP Chinese website!