What's the best way to break from nested loops in JavaScript?
Just like Perl,
loop1:
for (var i in set1) {
loop2:
for (var j in set2) {
loop3:
for (var k in set3) {
break loop2; // breaks out of loop3 and loop2
}
}
}
as defined in EMCA-262 section 12.12. [MDN Docs]
Unlike C, these labels can only be used for continue
and break
, as Javascript does not have goto
.
How to break nested loops in JavaScript?
You should be able to break to a label, like so:
function foo () {
dance:
for (var k = 0; k < 4; k++) {
for (var m = 0; m < 4; m++) {
if (m == 2) {
break dance;
}
}
}
}
How do I break out of nested loops in Java?
Like other answerers, I'd definitely prefer to put the loops in a different method, at which point you can just return to stop iterating completely. This answer just shows how the requirements in the question can be met.
You can use break
with a label for the outer loop. For example:
public class Test {
public static void main(String[] args) {
outerloop:
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (i * j > 6) {
System.out.println("Breaking");
break outerloop;
}
System.out.println(i + " " + j);
}
}
System.out.println("Done");
}
}
This prints:
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
Breaking
Done
Break statement not exiting all nested loops within JavaScript
You have to specify which loop you are breaking from.
loop1: for (i = 0; i < 5; i++) {
loop2: for (j = 0; j < 5; j++) {
if (i == 3) {
break loop1;
}
document.write(i + '*' + j + '<br>');
}
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break
Breaking out of an outer loop from an inner loop in javascript
Depending on what your conditionals are, it should be easy to set the iterator of your for-loop to something that would break it, and set your while condition to false. For example,
while(someBoolean){
for(var i = 0; i < size; i++){
if(wantToBreak){
i = size;
someBoolean = false;
}else{
//Do Stuff
}
}
}
Breaking out of nested loops
It has at least been suggested, but also rejected. I don't think there is another way, short of repeating the test or re-organizing the code. It is sometimes a bit annoying.
In the rejection message, Mr van Rossum mentions using return
, which is really sensible and something I need to remember personally. :)
breaking a nested loop
We can get this down to a one-liner, and it will do the early exit you want:
bool walletContainsUtilityToken = Wallets.Any(w => ExchangeFunctions.UtilityTokens.Any( ut => ut == w.Currency));
This one might be easier to understand (no nesting, only one -shorter- lambda):
bool walletContainsUtilityToken = Wallets.Select(w => w.Currency).Intersect(ExchangeFunctions.UtilityTokens).Any();
Taking the second option, for clarity I'd actually write it like this:
bool walletContainsUtilityToken = Wallets.
Select(w => w.Currency).
Intersect(ExchangeFunctions.UtilityTokens).
Any();
If you really want to continue using the full loop, I'd add a check to the loop conditions like so:
bool walletContainsUtilityToken = false;
for(int i = 0; i < Wallets.Length && !walletContainsUtilityToken; i++)
{
foreach (Currency ut in ExchangeFunctions.UtilityTokens)
{
if (Wallets[i].Currency.Equals(ut))
{
walletContainsUtilityToken = true;
break;
}
}
}
Finally, if these lists are large you could significantly improve performance by pre-arranging them into data structures for faster lookup (ie: a Dictionary, or even something that would support a binary search). But this is only a win if the lists are large enough.
Related Topics
Convert Hh:Mm:Ss String to Seconds Only in JavaScript
How to Check If an Element Is Really Visible with JavaScript
What Is the Cleanest Way to Get the Progress of Jquery Ajax Request
How to Conditionally Import an Es6 Module
How to Get the Day of Week and the Month of the Year
JavaScript Thousand Separator/String Format
Activexobject in Firefox or Chrome (Not Ie!)
Console Log the State After Using Usestate Doesn't Return the Current Value
Inspect Extension's Chrome.Storage in Devtools
Is the Promise Constructor Callback Executed Asynchronously
Pass Data or Modify Extension HTML in a New Tab/Window
What's the Difference Between Window.Location= and Window.Location.Replace()
How to Get the Day of Week and the Month of the Year
How to Change the Content of a <Textarea> with JavaScript
How to Capitalize First Letter of Each Word, Like a 2-Word City
How to Get Visitor's Location (I.E. Country) Using Geolocation