This is the 9th day of my participation in the August Wen Challenge.More challenges in August
The presence of the break and continue statements helped us optimize the code a lot, reducing the number of computations. But it’s easy to confuse their use.
break
I’ve got my answer, I don’t need to go through any more loops!
- The break statement immediately stops the current for, do while, while loop.
- Set the break position according to some condition until the loop can execute to the point where the break statement immediately stops execution and breaks out of the loop.
Pay attention to
- Break If there is no special instruction,You can only stop your own layer loop, not the outer loop. (Case 1)
- If you want to stop the outer loop, you canAdd a label name to the outer loop labelThe inner loop’s break keyword is followed by a space with a label name. (Case 2)
Case 1
for (var i = 1; i<=4; i++){ for (var j = 1; j<=4; j++){ console.log(i,j); if (j >= 2){ break; }}}Copy the code
Output:
We can see that the break only terminates the inner loop, the outer loop continues, and only the part of the inner loop that satisfies the if condition j>=2 is not executed
Case 2
lable: for (var i = 1; i<=4; i++){ for (var j = 1; j<=4; j++){ console.log(i,j); if (j >= 2){ break lable; }}}Copy the code
Output:
When the break tag is set to terminate the outer loop, you can see that all parts of I >=2 are not executed.
continue
That’s not the answer I was looking for, so let’s try the next one!
Encountering a continue indicates that the current loop data is not what we want, and immediately stops the current loop and enters the next one.
Pay attention to
- The position of the continue is set based on special conditions.
- Continue can only enter its next loop without special instructions, and cannot immediately stop the outer loop this time to enter the next one.
- Controls the outer loop in the same way as breaksAdd the outer label name. (Case 1)
Case 1
for (var i = 1; i<=4; i++){
for (var j = 1; j<=4; j++){
if (j >= 3){
continue;
}
console.log(i,j)
}
}
Copy the code
Output:
Case 2
lable: for (var i = 1; i<=4; i++){
for (var j = 1; j<=4; j++){
if (j >= 3){
continue lable;
}
console.log(i,j)
}
}
Copy the code
Output:
In the two examples, there is no difference between ending the inner or outer loop with continue.
summary
The break statement can break out of the current loop;
The break statement is usually accompanied by an if to terminate the loop prematurely if the condition is met;
The break statement always breaks out of the nearest loop;
The continue statement ends the loop prematurely;
The continue statement is usually accompanied by an if to prematurely end the loop if the condition is met.