Output from outer loop from inner loop in javascript

while(valid){ for(loop through associative array){ if(!valid){ break; } } } 

I tried to find a way to exit the while loop from the if statement. So far, the best method is the goto method, which does not exist in Javascript. What is the best way to make the if statement break out of both loops in which it is nested? Thanks in advance for your help!

+3
source share
2 answers

Depending on your conventions, it should be easy to set your for-loop iterator to something that broke it, and set the while condition to false. For instance,

 while(someBoolean){ for(var i = 0; i < size; i++){ if(wantToBreak){ i = size; someBoolean = false; }else{ //Do Stuff } } } 
+3
source

Creating a variable that acts as a flag to jump to the outer loop is one way, but JavaScript provides shortcuts that I think make code easier to read and also reduce the amount of code:

 outerloop: while(valid){ for(loop through associative array){ if(!valid){ break outerloop; } } } 

Here is some information about labels here. Scroll down to the labels section. You could even keep going out.

+2
source

Source: https://habr.com/ru/post/1238678/


All Articles