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

爱⌒轻易说出口 提交于 2019-11-29 11:07:29

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
        }
    }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!