【问题标题】:javascript object undefined errorjavascript对象未定义错误
【发布时间】:2014-01-11 13:47:45
【问题描述】:

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

【问题讨论】:

    标签: javascript ajax arrays json


    【解决方案1】:

    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 时才会迭代

    【讨论】:

    • 可能有_catCount,是分类项目数,如何防止出错
    【解决方案2】:

    在您提供的示例对象中,brands_cat 并不总是存在。当您迭代时,您需要先检查它是否存在,然后再检查对象树的任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2013-01-16
      相关资源
      最近更新 更多