jQuery跳过嵌套.each中父循环的迭代 [英] jQuery skip an iteration of the parent loop in nested .each

查看:55
本文介绍了jQuery跳过嵌套.each中父循环的迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下构造:

注意:此示例中的数组和目标只是符号!我知道此示例将有更好的解决方案-只是为了演示代码的构造.

Note: the arrays and the goal in this example are only symbolic! I know that there would be way better solutions for this example - it's just to demonstrate the construct of the code.

var firstArray = [1,2,3,4,5];
var secondArray = [1,2,4,5];

$.each(firstArray,function(i,firstArrayElement){
    $.each(secondArray,function(i,secondArrayElement){
        if(firstArrayElement === secondArrayElement) {
            // do stuff

            // PROBLEM: force the firstArray loop to continue with the next iteration
        }
    });
    console.log("Didn't find: "+firstArrayElement);
});

jsFiddle

要澄清我的问题:是否有一种方法可以强制父.each在下一次迭代中继续(=跳过 console.log )?在PHP中,这将是 continue 2; .因此,目标是,如果条件为真(在此示例中找到一个元素),则永远不要到达 console.log().

To clarify my question: Is there a way to force the parent .each to continue (= skip the console.log) with the next iteration? In PHP this would be continue 2;. So the goal is, to never reach the console.log() if a condition is true (in this example an element is found).

标志解决方案( jsFiddle ),但是必须有一种更好的方法来做到这一点.

There is the flag solution (jsFiddle), but there has to be a nicer way to do this.

还有带有标签的解决方案,但标签不适用于.each().

There are also solutions with labels but labels won't work with .each().

所以我要寻找的可能是一种在父函数中不带标志地使用 return 的方法.对于上面的示例,这将意味着结果记录:找不到3

So what I am looking for is probably a way to use return in the parent function without flags. For the example above, this would mean that the result logs: Didn't find 3

推荐答案

$.each 方法的响应始终是被迭代的对象.如果我们能够控制这一点,那将是一个选择.我们无法做到,您将无法逃脱标志解决方案.

The response of $.each method is always the object that was iterated. If we could control this, there would be an option. As we cannot, you won't be able to escape the flag solution.

如果您愿意至少在内部循环中放置 $.each ,并使用 for ,这应该可以完成工作:

If you're open to drop $.each, at least in the inner loop, and use for, this should do the job:

var firstArray = [1, 2, 3, 4, 5],
    secondArray = [1, 2, 4, 5];

$.each(firstArray,function(i, firstArrayElement) {
    var x = null;

    for (var j = 0; j < secondArray.length; j++) {
        var secondArrayElement = secondArray[j];

        if (firstArrayElement === secondArrayElement) {
            console.log('Do stuff');
            // return false here if you wan't to break after the first match.

        } else if (j + 1 == secondArray.length) {
            return false;
        }
    }

    console.log('Didn\'t find: ' + firstArrayElement);
});

这篇关于jQuery跳过嵌套.each中父循环的迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆