[英]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? 如果定义了数组中的任何元素且不为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? 是否有标准函数检查JavaScript中的null,undefined或空白变量?
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
). 在此代码中,我使用
Array.prototype.some
函数检查是否定义了任何元素(为此,我使用了一个名为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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.