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?
forEach will make the function to be executed for every valid element.!== avoids null although I must check.return will not help.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).
undefined"? You also then say "not null", so are you saying you also want anullcheck?