Reputation: 1385
There is a var that can be either an integer or an array of integers. I want to have a check that returns true when the var is not null or its array elements are null. The var can be:
a = null
or
a = [null, null]
The check
if (a != null)
returns true when
a = [null, null]
I want to avoid this. How can I do it in javascript, preferrably coffescript.
Upvotes: 0
Views: 77
Reputation: 968
Well, I guess it depends on whether a single null in the array is sufficient to fail the check. E.g, is [1,3, 5, null, 9] sufficient for that IF check above to return true? If so, then the suggestions above will work. If not, then you'll probably want to do something like this:
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!')
}
If the length is more than 1 then it's definitely not containing only nulls.
thnx,
Christoph
Upvotes: 0
Reputation: 3373
if (a instanceof Array) {
//check each index of a
} else {
//check only the a
}
Upvotes: 0
Reputation: 30638
you can check it as follow: following conditions will be required to test
if(a != null)
if (typeof a[index] !== 'undefined' && a.indexOf(null) == -1)
if (a[index] != null)
Upvotes: 0