Nested jQuery.each() - continue/break

后端 未结 11 491
天涯浪人
天涯浪人 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:54

    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.

提交回复
热议问题