0

I have an array object that looks like this:

var myArr = [undefined, undefined, undefined, undefined, undefined];

How can I loop through the array object and call a function if any one of the elements in the array is defined and not null?

  • Do you mean "defined" in the sense of the Array member exists, or "defined" in the sense of "exists, and not `undefined`"? You also then say "not null", so are you saying you also want a `null` check? – cookie monster Mar 22 '14 at 15:07

4 Answers4

2

If you don't care what the valid value is:

var myFunction = function(){console.log("array has valid values");};
var myArr = [undefined, undefined, undefined, undefined, 2];
var hasUndefined = myArr.some(function(item){
    return typeof item !== "undefined";
});
if (hasUndefined){
    myFunction();
}

If you need to find out what the valid items are:

var myFunction = function(validItems){
    console.log("array has valid values, and here they are:",validItems);
};
var myArr = [undefined, undefined, undefined, undefined, 2];
var validItems = myArr.filter(function(item){return typeof item !== "undefined";})
if (validItems.length){
    myFunction(validItems);
}
Remento
  • 897
  • 4
  • 6
1
var myArr = [null,undefined,4,5];

for (var i in myArr) {
    if (myArr[i]) {
        //Do something..
        return;
    }
}

I've also seen this which seems a very nice way.

[null,undefined,4,5].every(function(e) {
    if (e) {
        //Do something..
        return false;
    }
    else return true;
});

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Community
  • 1
  • 1
giannis christofakis
  • 7,151
  • 4
  • 48
  • 63
0

Try this

function isNotUndefined(item) {
    return typeof item != "undefined";
}

if (myArr.some(isNotUndefined)) {
   //do something
}

In this code I use the Array.prototype.some function to check if any element is defined (to do this I use an extra function called isNotUndefined).

exacs
  • 29
  • 3
0

Try this.

var myArr = [undefined, null, 123, undefined, null, 456];//for test
myArrFilterd = myArr.filter(function(x){return x!=null?true:false;});
myArrFilterd.forEach(function(x){console.log(x);/*something you want to do for each element*/});

output:

123
456
Kei Minagawa
  • 4,069
  • 2
  • 20
  • 37