javascript 对象未定义错误

标签 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 检查未定义时,

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/

相关文章:

javascript - 我如何生成一个带有按钮的文本框,以使用 js DOM 动态关闭它?

javascript - 使用钩子(Hook)检测 React 组件外部的点击

c - 调用数组的特定索引时,打印所有值

javascript - JQuery Post inside Promise inside every 如何创建数组

javascript - Polymer - 获取位于 Shadow dom 中的 div 位置

javascript - 在 karma.config.js 中包含插件后出错

javascript - 使用 UUID 时 Ajax 调用出错

javascript - 如何解析这种类型的文本?

javascript - ajax InvalidStateError : An attempt was made to use an object that is not, 或不再可用

arrays - 使用 Request 模块发布数组/对象