Nested jQuery.each() - continue/break

2019-01-13 19:45发布

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?

10条回答
爷的心禁止访问
2楼-- · 2019-01-13 20:21

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.

查看更多
看我几分像从前
3楼-- · 2019-01-13 20:24

Labeled Break

outerloop:
$(sentences).each(function() 
{
    $(words).each(function(i) 
    {
        break; /* breaks inner loop */
    } 
    $(words).each(function(i)  
    {
        break outerloop; /* breaks outer loop */
    }
}
查看更多
乱世女痞
4楼-- · 2019-01-13 20:31

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

查看更多
淡お忘
5楼-- · 2019-01-13 20:31

Unfortunately no. The problem here is that the iteration happens inside functions, so they aren't like normal loops. The only way you can "break" out of a function is by returning or by throwing an exception. So yes, using a boolean flag seems to be the only reasonable way to "break" out of the outer "loop".

查看更多
叛逆
6楼-- · 2019-01-13 20:33

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.

查看更多
爷的心禁止访问
7楼-- · 2019-01-13 20:38

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.

查看更多
登录 后发表回答