[英]javascript object undefined error
我有動態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"}
}
}
};
當我在循環中使用並檢查undefined時 ,效果很好
for(var i in Data.categories){
if(typeof Data.categories[i] == 'undefined'){
alert(i+"Cat undefined");
}
}
但是當我使用typeof檢查undefined時 ,
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對象
_catCount
中沒有brands_cat
。 所以,像這樣改變它
if (Data.brands_cat.hasOwnProperty("_catCount")) {
for (var i in Data.brands_cat._catCount) {
if(typeof Data.brands_cat._catCount[i].total == 'undefined') {
僅當找到該代碼時,它才會通過_catCount
進行迭代
在示例對象中,您提供的brands_cat並不總是存在。 迭代時,需要先檢查該對象是否存在,然后再檢查對象樹中的所有內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.