我有一个如下所示的数组对象:
var myArr = [undefined, undefined, undefined, undefined, undefined];
如何循环遍历数组对象并调用函数(如果有的话) 数组中的元素是否已定义且不为null?
答案 0 :(得分:2)
如果您不关心有效值是什么:
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();
}
如果您需要找出有效的项目:
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);
}
答案 1 :(得分:1)
var myArr = [null,undefined,4,5];
for (var i in myArr) {
if (myArr[i]) {
//Do something..
return;
}
}
我也看到了这个看起来非常好的方式。
[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?
答案 2 :(得分:0)
试试这个
function isNotUndefined(item) {
return typeof item != "undefined";
}
if (myArr.some(isNotUndefined)) {
//do something
}
在这段代码中,我使用Array.prototype.some
函数来检查是否定义了任何元素(为此我使用了一个名为isNotUndefined
的额外函数。)
答案 3 :(得分:0)
试试这个。
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*/});
输出:
123
456