Breaking out of an outer loop from an inner loop in javascript

后端 未结 2 1997
再見小時候
再見小時候 2020-12-19 14:40
while(valid){
   for(loop through associative array){
      if(!valid){
         break;
      }
   }
}

I have tried to find a way to break out of t

相关标签:
2条回答
  • 2020-12-19 15:06

    Creating a variable to act as a flag to pass to the outer loop is one way, however, JavaScript provides labels which I think makes the code easier to read as well as reduce the amount of code:

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

    Here's some info on labels here Scroll down to the label section. You could even do a continue to the outerloop.

    0 讨论(0)
  • 2020-12-19 15:17

    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
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题