When it comes to break, we all know that break is often used in writing loops. Here is a summary of some knowledge about break.
1. Traverse a large amount of data remember to use break to jump out of the loop
What do you mean? Simply put, when I have a thousand different disordered data arrays, I need to traverse them, but this data may be the first element or the last element.
Compare the following two pieces of code:
code 1:
var result;
for(var i = 0; i < 1000; i++) {
//arr and value "need" are already known
if(arr[i] == value_need) {
result = arr[i];
}
}
code 2:
var result;
for(var i = 0; i < 1000; i++) {
//arr and value "need" are already known
if(arr[i] == value_need) {
result = arr[i];
break;
}
}
The second one is better.
2. break just jumps out of a loop
Don't get this wrong.
var sum = 0;
for(var i = 0; i < 10; i++) {
for(var j = 0; j < 10; j++) {
if(j == 5) break;
sum++;
}
}
console.log('sum: ' + sum); //sum: 50
Do you see that i increases from 0 to 9, and j increases 5 times from 0 to 4 each time. A total of 50. If it can jump out of multiple loops, sum should be 5.
Now that I've said break, I'd like to say continue by the way.
code 1:
var sum = 0;
for(var i = 0; i < 10; i++) {
if(i == 5) continue;
sum++;
}
console.log('sum: ' + sum); //sum: 9
code 2:
var sum = 0;
for(var i = 0; i < 10; i++) {
for(var j = 0; j < 10; j++) {
if(i == 5 && j == 5) continue;
sum++;
}
}
console.log('sum: ' + sum); //sum: 99
See, that is to skip this cycle.
3. Jump out of multiple loops
break and tag statements are needed to work. The syntax of a label statement is this: Label: statement.
var sum = 0;
outState:
for(var i = 0; i < 10; i++) {
for(var j = 0; j < 10; j++) {
if(j == 5) break outState;
sum++;
}
}
console.log('sum: ' + sum); //sum: 5
See? If i execute it five times when i is 0, i will jump out of the whole double cycle.
Take a look at continue's:
var sum = 0;
outState:
for(var i = 0; i < 10; i++) {
for(var j = 0; j < 10; j++) {
if(j == 5) continue outState;
sum++;
}
}
console.log('sum: ' + sum); //sum: 50
Every time j to 5, i don't do it. Go to the outer i loop. i go from 0 to 9, five times at a time, that's 50.