简体   繁体   中英

How can I loop through an array object and check each element to see if one is defined?

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?

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);
}
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?

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 ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM