Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
695 views
in Technique[技术] by (71.8m points)

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

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

I have tried to find a way to break out of the while loop from the if statement. So far, the best method seems to be the goto method that is non-existant in Javascript. What is the best way to cause the if statement to break out of both of the loops it is nested in? Thanks in advance for the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...