如果给定的数组不包含给定的值,我希望打开一个确认对话框。然而,以下工作,我对中间变量 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/