javascript对象未定义错误

时间:2014-01-11 13:47:46

标签: javascript ajax arrays json

我有动态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检查 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对象

2 个答案:

答案 0 :(得分:1)

_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

答案 1 :(得分:0)

在示例对象中,您给brands_cat并不总是存在。当你迭代时,你需要在检查对象树下面的任何东西之前先检查它是否存在。