gpt4 book ai didi

javascript 对象未定义错误

转载 作者:行者123 更新时间:2023-11-28 01:39:42 24 4
gpt4 key购买 nike

我有动态 AJAX JSON 响应对象数据变量

 var Data = {"categories":
[
{"Id":"2","CategoryName":"Womens"},
{"Id":"3","CategoryName":"Mens"},{"Id":"4","CategoryName":"Kids"},
{"Id":"5","CategoryName":"Home"},{"Id":"6","CategoryName":"Health and Beauty"},
{"Id":"7","CategoryName":"Seasonal Events"},{"Id":"10","CategoryName":"Model Shots"},
{"Id":"11","CategoryName":"Product Shots"},
{"Id":"12","CategoryName":"Accessories"},
{"Id":"13","CategoryName":"Tops"},{"Id":"14","CategoryName":"Spuds"},
{"Id":"15","CategoryName":"EVIAN"}
],
"brands_cat":{
"_bandCount":{"171": "BrandId" : "171", "ArchiveName": "HP",
"img_from_archive":"7"}
}
}
};

当我在循环中使用并检查未定义时,工作正常

for(var i in Data.categories){
if(typeof Data.categories[i] == 'undefined'){
alert(i+"Cat undefined");
}
}

但是当我使用 typeof 检查未定义时,

for(var i in Data.categories){
if(typeof Data.brands_cat._catCount[i].total == 'undefined'){
alert(i+"Cat total undefined");
}
}

它给出了错误

TypeError: Data.brands_cat._catCount is undefined

是否可以使用 typeof 关键字检查未定义的多级 JSON 对象

最佳答案

brands_cat 中没有 _catCount。所以,像这样改变它

if (Data.brands_cat.hasOwnProperty("_catCount")) {
for (var i in Data.brands_cat._catCount) {
if(typeof Data.brands_cat._catCount[i].total == 'undefined') {

仅当找到_catCount时,此代码才会迭代

关于javascript 对象未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21063031/

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