2014-01-11 26 views
1

動態AJAX JSON Response對象數據變量我有JavaScript對象未定義的錯誤

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檢查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關鍵字

回答

1

brands_cat中沒有_catCount。因此,只有當它被發現

+0

有可能'_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迭代,它是類的項目數,因此如何從錯誤 – Girish

+0

@GirishJangid防止請檢查我更新的答案。 – thefourtheye

+0

它爲我工作,返回'true'' false'謝謝 – Girish

0

在該示例未定義多JSON對象的對象,你給brands_cat並不總是存在。當你迭代時,你需要首先檢查它的存在性,然後再檢查對象樹下面的任何東西。

相關問題