如果给定的数组不包含给定值,我希望打开一个确认对话框。但是,下面的工作,我对中间变量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');
}
});
答案 0 :(得分:3)
您可以使用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');
}
答案 1 :(得分:0)
您可以改用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');
}
});
答案 2 :(得分:0)
另一个更易读的解决方案:
$(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');
}
}
});