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 option
s 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
});
}
}
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With