Nested jQuery.each() - continue/break
Solution 1
You should do this without jQuery, it may not be as "pretty" but there's less going on and it's easier to do exactly what you want, like this:
var sentences = [
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
'Vivamus aliquet nisl quis velit ornare tempor.',
'Cras sit amet neque ante, eu ultrices est.',
'Integer id lectus id nunc venenatis gravida nec eget dolor.',
'Suspendisse imperdiet turpis ut justo ultricies a aliquet tortor ultrices.'
];
var words = ['ipsum', 'amet', 'elit'];
for(var s=0; s<sentences.length; s++) {
alert(sentences[s]);
for(var w=0; w<words.length; w++) {
if(sentences[s].indexOf(words[w]) > -1) {
alert('found ' + words[w]);
return;
}
}
}
You can try it out here. I'm not sure if this is the exact behavior you're after, but now you're not in a closure inside a closure created by the double .each()
and you can return
or break
whenever you want in this case.
Solution 2
There are a lot of answers here. And it's old, but this is for anyone coming here via google. In jQuery each function
return false;
is like break
.
just
return;
is like continue
These will emulate the behavior of break and continue.
Solution 3
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
Solution 4
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.
Solution 5
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.
Related videos on Youtube
Ryan Kinal
Web developer and web-programming enthusiast, likes to keep up with current trends. I'm employed at McKissock Education working with the Microsoft .NET stack, and I have a super-exciting startup company: SlickText.com is a leader in the SMS marketing industry providing businesses and organizations all over the United States with an incredibly easy and affordable solution for sending targeted, opt-in text messages to their customers. For some other stuff, check out these links: My GitHub GMScreen Certified Random My SoundCloud
Updated on March 12, 2020Comments
-
Ryan Kinal over 4 years
Consider the following code:
var sentences = [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Vivamus aliquet nisl quis velit ornare tempor.', 'Cras sit amet neque ante, eu ultrices est.', 'Integer id lectus id nunc venenatis gravida nec eget dolor.', 'Suspendisse imperdiet turpis ut justo ultricies a aliquet tortor ultrices.' ]; var words = ['ipsum', 'amet', 'elit']; $(sentences).each(function() { var s = this; alert(s); $(words).each(function(i) { if (s.indexOf(this) > -1) { alert('found ' + this); return false; } }); });
The interesting part is the nested jQuery.each() loops. As per the documentation, returning false will break out of the loop (discontinuing execution of the loop - similar to a normal JavaScript break statement), and returning non-false will stop the current iteration and continue with the next iteration (similar to a normal JavaScript continue statement).
I can break or continue a jQuery.each() on its own, but with nested jQuery.each, I've found it difficult to break out of the parent loop from within the child loop. I could use a boolean value, and update it on every child iteration, but I was wondering if there was an easier way.
I've set up an example at jsFiddle if you'd like to mess around with it. Simply click the "Test" button to run the example shown above.
TLDR: Is there anything resembling a labeled continue or break within the context of jQuery?
-
Nick Craver almost 14 yearsIt looks like you're over-using jQuery here, a simple
for
loop will do what you want :) -
Ryan Kinal almost 14 yearsThis is a much simplified example. In reality, I'm looping over jQuery-selected DOM nodes, etc.
-
-
Ryan Kinal almost 14 yearsWow. This may be a blatant misuse of try/catch, but it works.
-
Ryan Kinal almost 14 yearsVery good point. Even with the more complicated use of jQuery DOM selectors that makes up my actual use-case, they can be iterated over normally.
-
spinon almost 14 years@Ryan yeah I know. It completely goes against what/how we are taught to do things. But I was just trying to propose a solution.
-
spinon almost 14 yearsGlad to help then. Surprised not really any thrashing. Must be light today or my self acknowledgment of the not best practice approach.
-
Ryan Kinal almost 14 yearsAlmost gave you the check on this one, but it felt too dirty :-D Seriously, though, clever solution.
-
Ryan Kinal almost 14 yearsNormal JavaScript gets the check. Man, I love this language.
-
BobRodes over 11 yearsI like it too! This is exactly why we call it "throwing an exception" now instead of "raising an error". One need only change "Exit Error" to a more diplomatic "Exit condition encountered" or some such, and we have laundered the concept and made it politically correct. :) One might say (if one is given to spin doctoring) that the rule here is that one loops "except" when an exit condition is encountered, at which point one throws an exception.
-
Ryan Kinal over 11 yearsPlease see Serj's answer. It's downvoted because you can't have a labeled
return true
orreturn false
-
Thihara over 11 yearsactually I tried return true in firefox and it was the same as break for me. Which is the reason for my answer.
-
nalply over 11 yearsDoes it really work? Labeled breaks over function boundaries?
-
jave.web over 10 years$(selector).each() VS $.each(set) - I hope it works the same :)
-
Mr Mikkél about 10 yearsThat doesn't break out of a nested loop.
-
Legna over 8 yearsthis solution is impeccably correct, but it does not address the stated question. It does not explain how to break out of a chain of nested 'each' loops. thus -1 (sorry)
-
mhodges about 8 years@Legna Yes it does... Nick says you can return (break from both loops) or break (break from inner loop) using this solution.
-
bharal over 5 yearsthis is really nice, it is a shame that all the other answers - which aside from the selected answer are just wrong have been upvoted.