Preface
Common ways to traverse arrays in JavaScript are:for
、for-of
、forEach
、map
etc. When we loop the array, in some cases, we will exit the loop early and terminate the iteration, such as: the target element has been found, or a certain condition is met, which can avoid unnecessary calculations and optimize program performance.
1. Common exit loop method
There are two ways to exit the loop in JavaScript:break
andcontinue
;
-
break
: Terminate all loops immediately and execute the code after the loop. -
continue
: Immediately terminate the current loop and start the next loop.
1-1 Use break to break out of the loop
Example:
for (let i = 0; i < 10; i++) { if (i === 5) { break; // When i equals 5, the loop will jump out } (i); // Output 0, 1, 2, 3, 4} ('break break out of the for loop');
1-2 Use continue to jump out of the loop
Example:
for (let i = 0; i < 10; i++) { if (i === 5) { continue; // When i equals 5, the current loop is skipped and the next loop is performed } (i); // Output 0, 1, 2, 3, 4, 6, 7, 8, 9, no 5}
2. Can forEach and Map break out of the loop
We have already introduced it abovefor
It can break out of the loop, thenforEach
、Map
Can you break out of the loop?
First we usebreak
、continue
;
Example:
const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; _array.forEach((item) => { if (item === 5) { //break;//Jump target cannot cross function boundary //continue;//Jump target cannot cross function boundaryS } (item); });
You can seebreak
、continue
Cannot be used in functions anymore.forEach
、map
A function is set to each element during the loop.
We're tryingreturn
method.
Example:
//Method 1const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; _array.forEach((item) => { if (item === 5) { return; // Skip when i equals 5 } (item); // 0,1,2,3,4,6,7,8,9 }); //Method 2, use return in the functionfunction testReturn() { const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; _array.forEach((item) => { if (item === 5) { return; // Skip when i equals 5 } (item); // 0,1,2,3,4,6,7,8,9 }); } testReturn();
return
A statement is used to terminate function execution, and can only jump out of the current function. We checked MDN and found onethrow
.
3 powerful throw
throw
Statements are used to throw user-defined exceptions. The execution of the current function will be stopped (throw
The subsequent statement will not be executed), and control will be passed to the first one in the call stackcatch
piece.
Example:
let result = 0; try { ( 'First execute the code in the try block, if it throws an exception, the code in the catch block will be executed. ' ); const _array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; _array.forEach((item) => { if (item === 5) { throw item; //**Top Error** } (item); //0,1,2,3,4 }); } catch (e) { ('Catch gives e:' + e); //Catch gives e:5 result = e; } finally { ('The code in the finally block is always executed before exiting:' + result); //The code in finally block is always executed before exiting: 5} (result); //Wait until the value we want is 5
We found that throw can jump out of the loop.
Now let's make a simple summary:
1. Can be usedbreak
Just jump out of the loop directly;
2. Can be usedcontinue
Skip the current loop and enter the next loop;
3. Can be usedreturn
Exit the current function execution;
4. Can be usedtry-catch-throw
Forced exit from the loop.
4. How to exit nested loop
I often encounter some nested data at work. When we find the data we want, in order to save time, we consider how to exit the loop.
4-1 Use break to break out of nested loop
Example:
for (let i = 0; i <= 5; i++) { for (let j = 0; j <= 5; j++) { if (j === 3) { break; //continue; } (`i: ${i}, j: ${j}`); } // The `break` statement is used to immediately terminate the innermost loop and continue to execute the next statement. ('Breaking out of break, pointing here'); } //i: 0, j: 0 // i: 0, j: 1 // i: 0, j: 2 // Bounce out of break and point here// i: 1, j: 0 // i: 1, j: 1 // i: 1, j: 2 // Bounce out of break and point here
break
Only the innermost loop can be jumped out, but not the multi-layer loop
4-2 Use return to jump out of nested loop
Example:
function testReturn() { for (let i = 0; i <= 5; i++) { for (let j = 0; j <= 5; j++) { if (j === 3) { return { i, j }; } (`i: ${i}, j: ${j}`); } } } (testReturn()); //i: 0, j: 0 // i: 0, j: 1 // i: 0, j: 2 // {i: 0,j: 3}
The return statement is used to terminate function execution and can break out of multi-layer loops
4-3 Use try-catch-throw to jump out of nested loop
Example:
let result = 0; try { for (let i = 0; i < 5; i++) { for (let j = 0; j < 5; j++) { if (j === 3) { throw j; } (`i: ${i}, j: ${j}`); } } } catch (e) { ('Catch gives e:' + e); //The catch gives e:3 result = e; } (result); //3 //i: 0, j: 0 //i: 0, j: 1 //i: 0, j: 2 //The catch gives e:3//3
try-catch-throw
Multi-layer loops can also be broken
4-4 Use the tag statement outerLoop
Example:
outerLoop: for (let i = 0; i <= 5; i++) { for (let j = 0; j <= 5; j++) { if (j === 3) { break outerLoop; // Break out of the outer loop } (`i: ${i}, j: ${j}`); } } //i: 0, j: 0 //i: 0, j: 1 //i: 0, j: 2
In this example,outerLoop
is a tag that marks the outer layerfor
cycle. When the inner layerif
When the conditions are met,break outerLoop;
The statement will jump outouterLoop
at the label, thus terminating the execution of the two-layer loop.
Now let's make a simple summary:
1. You can throw nested loops into a function and usereturn
Just jump out of the function directly and jump out of the loop;
2. Can be usedbreak
CooperateouterLoop
Break out of the loop;
3. Can be usedtry-catch-throw
Forced exit from the loop.
5. Methods in the array that can end iteration in advance
- Every: All satisfied.Then just return false and end early.
- Some: At least one element is satisfied.Then just return true and end early.
- find, findIndex, include, etc.: end early if the conditions are met;
const _array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; ('every'); _array.every((item) => { if (item == 2) { return false; //Return false if the condition is not met } (item); //1 }); ('some'); _array.some((item) => { if (item == 2) { return true; //A satisfying returns true } (item); //1 }); ('find'); const found = _array.find((item) => item === 2); (found); //2 ('findIndex'); const findIndex = _array.findIndex((item) => item === 2); (findIndex); //1
6. Final summary
- Preferential ways to use arrays:
includes
、every
、some
wait; - Considering using
break
、continue
Break out of the loop; -
return
Bounce out of functions is also an option; - As for the exception
try-catch-throw
Multi-layer loops can be exited under special circumstances and are not recommended to use them frequently. - at last
outerLoop
Combinedbreak
Use with caution;
Summarize
This is the article about the common methods of JavaScript to jump out of loops. For more related content on JS to jump out of loops, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!