Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested jQuery.each() - continue/break

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?

like image 863
Ryan Kinal Avatar asked Jul 16 '10 17:07

Ryan Kinal


People also ask

How to use break in each loop jQuery?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.

Does Break leave all loops?

In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

How do you break a loop in Cypress?

You can stop the . each() loop early by returning false in the callback function.


1 Answers

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.

like image 75
Thihara Avatar answered Oct 19 '22 23:10

Thihara