Return 来自 jQuery $.each 循环

Return from a jQuery $.each loop

如果给定的数组不包含给定的值,我希望打开一个确认对话框。然而,以下工作,我对中间变量 t 的使用似乎有点过分,我希望有一种更优雅的方法来做到这一点。我可以从 $.each 循环 return 并导致上游匿名函数 return false 吗?

$(function(){
    myArr=[['de'],['df','de'],['df','dz'],['de']];
    if((function(){
        var t=true;
        $.each(myArr, function() {
            console.log($.inArray('de', this)=='-1');
            if($.inArray('de', this)=='-1') {t=false;return false;};    //Doesn't return true to parent
        })
        return t;
        })() || confirm("Continue even though one of the choices doesn't contain 'de'?") ){
        console.log('proceed');
    }
});

你可以使用Array.prototype.some的方法,它会让代码更全面更简单:

var myArr=[['de'],['df','de'],['df','dz'],['de']];

if (myArr.some(function(el) {
    return el.indexOf('de') === -1;
}) && confirm("Continue even though one of the choices doesn't contain 'de'?")) {
    document.write('proceed');
}

您可以改用 grep,过滤掉包含 'de' 的值,然后计算剩余的值:

$(function(){
    var myArr=[['de'],['df','de'],['df','dz'],['de']];
    var notDe = $.grep(myArr, function(item, index) {
            return ($.inArray('de', this)=='-1');
        });
    if(notDe.length == 0 || confirm("Continue even though one of the choices doesn't contain 'de'?") ){
        console.log('proceed');
    }
});

另一个更具可读性的解决方案:

$(function () {
    myArr = [
        ['de'],
        ['df', 'de'],
        ['df', 'dz'],
        ['de']
    ];

    var t = 0;
    $.each(myArr, function (k, v) {
        if ($.inArray('de', v) === -1) {
            t++;
        }
    });

    if (t > 0) {
        if (confirm("Continue even though " + t + " of the choices do not contain 'de'?")) {
            console.log('proceed');
        }
    }
});