javascript - 从 jQuery $.each 循环返回

标签 javascript jquery anonymous-function

如果给定的数组不包含给定的值,我希望打开一个确认对话框。然而,以下工作,我对中间变量 t 的使用似乎有点过分,我希望有一种更优雅的方式来做到这一点。我可以从 $.each 循环返回并导致上游匿名函数返回 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');
}

关于javascript - 从 jQuery $.each 循环返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29050709/

相关文章:

php - FullCalendar - 限制范围

javascript - 在 Accordion 中打开外部菜单项时,无法将新的颜色类添加到第一个子菜单项

php - 在 PHP 的匿名函数中包装变量

javascript - 如何在 CoffeeScript 中将两个匿名函数作为参数传递?

Scala IDE 警告 : "anonymous function convertible to method value"

javascript - 如何编写服务层规范?

jquery - 如何在 jQuery Mobile 中以编程方式切换导航栏选项卡?

php - 验证粘贴在字段中的脚本

javascript - HTML5 移动键盘覆盖全屏模式下的输入

javascript - SQL生成的选择菜单,根据相关值更新文本框