I have the following scenario:
$.each(array, function() {
...
$.each(array1, function() {
if condition () { }
});
});
How can I break out of outer each
loop when my condition evaluates to true inside the inner each
loop?
Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.
Technically the correct answer is to label the outer loop. In practice if you want to exit at any point inside an inner loop then you would be better off externalizing the code into a method (a static method if needs be) and then call it. That would pay off for readability.
In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
Another way of breaking out of multiple loops is to initialize a flag variable with a False value. The variable can be assigned a True value just before breaking out of the inner loop. The outer loop must contain an if block after the inner loop. The if block must check the value of the flag variable and contain a break statement.
We can do that by using a labeled break: A labeled break will terminate the outer loop instead of just the inner loop. We achieve that by adding the myBreakLabel outside the loop and changing the break statement to stop myBreakLabel. After we run the example we get the following result:
If the inner loop terminates due to a break statement given inside the inner loop, then the else block after the inner loop will not be executed and the break statement after the else block will terminate the outer loop also.
Program 2: PHP program to search a number in an array and break the outer loop when it is found. Using goto keyword: The goto keyword is used to jump the section of the program. It jumps to the target label. Program 3: PHP program to break the outer loop using goto keyword.
$.each(array, function() {
var flag = true;
$.each(array1, function() {
if (condition) {
flag = false;
return false;
}
});
return flag;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With