简体   繁体   English

javascript对象未定义错误

[英]javascript object undefined error

I have Dynamic AJAX JSON Response object Data variable 我有动态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"}
                      }
    }
  };

When i used in loop and check undefined , works fine 当我在循环中使用并检查undefined时 ,效果很好

for(var i in Data.categories){
   if(typeof Data.categories[i] == 'undefined'){
       alert(i+"Cat undefined");
   }
}

But when i used typeof to check undefined , 但是当我使用typeof检查undefined时

for(var i in Data.categories){
       if(typeof Data.brands_cat._catCount[i].total == 'undefined'){
           alert(i+"Cat total undefined");
       }
    }

And it gave error 它给了错误

TypeError: Data.brands_cat._catCount is undefined

Is it possible to check multilevel JSON object undefined with typeof keyword 是否可以使用typeof关键字检查未定义的多层JSON对象

There is no _catCount in brands_cat . _catCount中没有brands_cat So, change it like this 所以,像这样改变它

if (Data.brands_cat.hasOwnProperty("_catCount")) {
    for (var i in Data.brands_cat._catCount) {
        if(typeof Data.brands_cat._catCount[i].total == 'undefined') {

This code will iterate through _catCount only if it is found 仅当找到该代码时,它才会通过_catCount进行迭代

Within the example object you gave brands_cat does not always exist. 在示例对象中,您提供的brands_cat并不总是存在。 When you iterate you need to check for the existence of that first prior to checking anything further down the object tree. 迭代时,需要先检查该对象是否存在,然后再检查对象树中的所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM