如何检查如果var是空的时候,它可以是空的数组

how to check if var is null when it can be array of nulls

本文关键字:数组 何检查 检查 如果 var      更新时间:2023-09-26

var可以是整数或整数数组。我希望有一个检查,当var不为空或其数组元素为空时返回真。变量可以是:

a = null

a = [null, null]

检查

if (a != null)

返回true
a = [null, null]

我想避免这个。我如何在javascript中做到这一点,最好是coffescript。

我从elclars中使用了if (a.a indexof (null) == -1)。谢谢你!

您可以按如下方式检查:测试

需要以下条件
if(a != null)
if (typeof a[index] !== 'undefined' && a.indexOf(null) == -1) 
if (a[index] != null)
if (a instanceof Array) {
   //check each index of a
} else {
    //check only the a
}

嗯,我想这取决于数组中的单个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,那么它肯定不只是包含null。

感谢,
Christoph