0

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.

2
  • 2
    Try if (a.indexOf(null) == -1) Commented Mar 27, 2014 at 12:44
  • use undefine when you want an undefined integer, null is always an empty object Commented Mar 27, 2014 at 12:46

4 Answers 4

1

I used if (a.indexOf(null) == -1) from elclanrs . Thank you!

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0
if (a instanceof Array) {
   //check each index of a
} else {

    //check only the a
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.