有一个var可以是整数或整数数组。我希望有一个检查,当var不为null或其数组元素为null时返回true。 var可以是:
a = null
或
a = [null, null]
支票
if (a != null)
时
返回true
a = [null, null]
我想避免这种情况。我怎样才能在javascript中完成它,最好是coffescript。
答案 0 :(得分:1)
我使用了来自elclanrs的if(a.indexOf(null)== -1)。谢谢!
答案 1 :(得分:0)
您可以按照以下方式检查:测试
需要以下条件if(a != null)
if (typeof a[index] !== 'undefined' && a.indexOf(null) == -1)
if (a[index] != null)
答案 2 :(得分:0)
if (a instanceof Array) {
//check each index of a
} else {
//check only the a
}
答案 3 :(得分:0)
嗯,我想这取决于数组中的单个null是否足以使检查失败。例如,[1,3,5,null,9]是否足以使上述IF检查返回true?如果是这样,那么上述建议将起作用。如果没有,那么你可能想做这样的事情:
Array.prototype.unique = [].unique || function (a) {
return function () {
return this.filter(a)
};
}(function(a,b,c) {
return c.indexOf(a,b + 1) < 0
});
var nullArray = [null, null, null, null],
notNullArray = [null, 1, null, 2],
filtered;
if(( filtered = nullArray.unique()) && (filtered.length == 1) && (filtered[0] == null)) {
// NULL VALUE
alert( 'NULL!')
} else {
// SAFE TO WORK WITH
alert('NOT NULL!')
}
if(( filtered = notNullArray.unique()) && (filtered.length == 1) && (filtered[0] == null)) {
// NULL VALUE
alert( 'NULL!')
} else {
// SAFE TO WORK WITH
alert('NOT NULL!')
}
如果长度超过1,则它绝对不包含空值。
日Thnx,
克里斯托弗