Click here to view: full tutorial, source code and accompanying video
Contents of this article
1. Background
Considering such a usage scenario, we need to write a program to calculate the first number within 1 to 10000 that is divisible by both 123 and 18.
According to the techniques we learned earlier, we can use a for loop to process, the code is as follows:
for (var i = 1; i <= 10000; i++) {
//从1到10000遍历
if (i % 123 == 0 && i % 18 == 0) {
//同时被123和18整除
console.log(i);
}
}
At this point we open the browser console and find the output as follows. We want to find the first number that meets the requirements, that is, we can find 738, but in fact, the program continues to search until i is greater than 10000.
That is to say, starting from 739 to 10,000, all these jobs are done for nothing, meaningless, wasting the computing power of the computer.
So we need to end the loop early after finding 738.
2. Use break to break out of the loop
The function of break is that when the program executes the break code, it will jump out of the loop statement where the break is located, that is, directly jump out of the for/while loop.
Our modified code is as follows:
for (var i = 1; i <= 10000; i++) {
//从1到10000遍历
if (i % 123 == 0 && i % 18 == 0) {
//同时被123和18整除
console.log(i);
break; //跳出循环
}
}
// xxx
When the value of i reaches 738, the if condition judgment is satisfied, so console.log(i);
the value of i is output, and then the execution break;
jumps out of the for loop, so it will jump //xxx
everywhere to execute the subsequent statements outside the loop.
3. Use break in while
In the above example, we demonstrate the use of break in the for loop, and the while loop can also use break, the code is as follows:
var i = 1;
while (i <= 10000) {
if (i % 123 == 0 && i % 18 == 0) {
//同时被123和18整除
console.log(i);
break; //跳出循环
}
i++;
}
4. Summary
Using break, we can end our work early, without having to stubbornly execute to the end. For example, we need to recruit a JavaScript software development engineer. After we find one, we can end the recruitment process, instead of endlessly recruiting.