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
source share