Nested jQuery.each() - continue/break

后端 未结 11 515
天涯浪人
天涯浪人 2020-12-05 03:52

Consider the following code:

    var sentences = [
        \'Lorem ipsum dolor sit amet, consectetur adipiscing elit.\',
        \'Vivamus aliquet nisl quis          


        
11条回答
  •  情书的邮戳
    2020-12-05 04:49

    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.

提交回复
热议问题