Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit (escape) a function from for loop inside of it?

This is theoretical question to understand how many escapes (return or exit) can apply to nested loops or other controls and functions.

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

I can't stop iterating over options in select element.

I tried return and return false already, but am unsuccesful.

Generally how we can do that?

function() {
    for (...) {
        if (...) {
            $(...).each(function() {
               // You have to exit outer function from here
            });
        }
    }
}
like image 543
caglaror Avatar asked Mar 25 '13 12:03

caglaror


2 Answers

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

like image 149
Konstantin Dinev Avatar answered Oct 22 '22 03:10

Konstantin Dinev


I would do it this way:

  • Create a boolean variable to check on each loop, and if the variable is true, then 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 not the correct use of a try-catch as a try-catch should strictly be used for error handling, not jumping to different sections of your code - but it will work for what you're doing.

If return is not doing it for you, try using a 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

like image 42
What have you tried Avatar answered Oct 22 '22 02:10

What have you tried