Consider the following code:
var sentences = [
\'Lorem ipsum dolor sit amet, consectetur adipiscing elit.\',
\'Vivamus aliquet nisl quis
You can break the $.each() loop at a particular iteration by making the callback function return false.
Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
As is stated in the jQuery documentation http://api.jquery.com/jQuery.each/
return true in jQuery.each is the same as a continue
return false is the same as a break
The problem here is that while you can return false from within the .each callback, the .each function itself returns the jQuery object. So you have to return a false at both levels to stop the iteration of the loop. Also since there is not way to know if the inner .each found a match or not, we will have to use a shared variable using a closure that gets updated.
Each inner iteration of words refers to the same notFound variable, so we just need to update it when a match is found, and then return it. The outer closure already has a reference to it, so it can break out when needed.
$(sentences).each(function() {
var s = this;
var notFound = true;
$(words).each(function() {
return (notFound = (s.indexOf(this) == -1));
});
return notFound;
});
You can try your example here.
I've used a "breakout" pattern for this:
$(sentences).each(function() {
var breakout;
var s = this;
alert(s);
$(words).each(function(i) {
if (s.indexOf(this) > -1)
{
alert('found ' + this);
return breakout = false;
}
});
return breakout;
});
This works nicely to any nesting depth. breakout is a simple flag. It will stay undefined unless and until you set it to false (as I do in my return statement as illustrated above). All you have to do is:
var breakout;return false statement(s): return breakout = falseNot too inelegant, right? ...works for me anyway.
There is no clean way to do this and like @Nick mentioned above it might just be easier to use the old school way of loops as then you can control this. But if you want to stick with what you got there is one way you could handle this. I'm sure I will get some heat for this one. But...
One way you could do what you want without an if statement is to raise an error and wrap your loop with a try/catch block:
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)
}
Ok, let the thrashing begin.