How to exit a function from a loop inside?

It is a theoretical question to understand how many shoots (return or exit) can be applied to nested loops or other controls and functions.

I got confused about this because I was stuck in the code How to escape from ... for each loop and method at the same time?

I cannot stop the repetition with option in the select element.

I already tried return and return false , but did not result in an error.

How can we do this?

 function() { for (...) { if (...) { $(...).each(function() { // You have to exit outer function from here }); } } } 
+6
source share
4 answers

Use a shared variable between loops. Flip it to true at the end of each() loop if you want to exit, and at the end of the for-loop check it will be true . If so, break out of it.

+7
source

I would do it like this:

  • Create a boolean variable to test each loop, and if the variable is true, exit the loop (do this for each).

     var exitLoop = false; $(sentences).each(function() { if(exitLoop) {return;} var s = this; alert(s); $(words).each(function(i) { if(exitLoop) {return;} if (s.indexOf(this) > -1) { alert('found ' + this); throw "Exit Error"; } }); }); 

Note this is the wrong use of try-catch , since try-catch should be strictly used to handle errors, and not to jump to different sections of your code, but this will work for what you do.

If return doesn't do it for you, try using try-catch

 try{ $(sentences).each(function() { var s = this; alert(s); $(words).each(function(i) { if (s.indexOf(this) > -1) { alert('found ' + this); throw "Exit Error"; } }); }); } catch (e) { alert(e) } 

Code taken from this answer

+1
source

The loop can also be inferred by changing the value of the iterator.

 var arr = [1,2,3,4,5,6,7,8,9,10]; for(var i = 0;i<arr.length;i++){ console.log(i); compute(i); function compute(num){ //break is illegal here //return ends only compute function if(num>=3) i=arr.length; } } 
+1
source

As in most languages. Keyword to exit the loop: break; More details here: http://www.w3schools.com/js/js_break.asp

-3
source

All Articles