gpt4 book ai didi

javascript - 如何循环遍历数组对象并检查每个元素以查看是否已定义?

转载 作者:行者123 更新时间:2023-11-28 19:55:51 24 4
gpt4 key购买 nike

我有一个如下所示的数组对象:

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

如何循环遍历数组对象并调用函数(如果有)数组中的元素已定义且不为 null?

最佳答案

如果您不关心有效值是多少:

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

关于javascript - 如何循环遍历数组对象并检查每个元素以查看是否已定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22579068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com