循环遍历JSON数组时显示"undefined"结果。

14 浏览
0 Comments

循环遍历JSON数组时显示"undefined"结果。

这个问题已经有了答案:

为什么使用“for...in”进行数组迭代是一个坏主意?

JavaScript for...in vs for

我有一个JSON字符串被解析(在response变量中)从AJAX中:

JSON

{
   "TheArray":[  
      {  
         "AlmostThere": {  
            "whatWeAreLookingFor":"Hello"
         }
      },
      {
        "AlmostThere": {
            "whatWeAreLookingFor":"Goodbye"
        }
      }
   ]
}

被解析的JSON

var jsonData = JSON.parse(response); //response is the string version of the JSON code!

现在,我需要循环进入JSON数组,这里被称为TheArray 我这样做:

循环TheArray

for (var contents in jsonData["TheArray"]) {
}

在里面,我们得到whatWeAreLookingFor元素的值:

for (var contents in jsonData["TheArray"]) {
    console.log(contents.whatWeAreLookingFor + "!");
}

但是有一个问题!控制台输出... undefined!

我尝试了多种方法来使这个工作,比如使用contents[\"whatWeAreLookingFor\"]等等,但我仍然得到相同的结果。

admin 更改状态以发布 2023年5月22日
0
0 Comments

如果你用你自己的方式循环数组TheArray,那么contents变量将变成这两个对象:

{  
     "AlmostThere": {  
        "whatWeAreLookingFor":"Hello"
     }
}

{
    "AlmostThere": {
        "whatWeAreLookingFor":"Goodbye"
    }
}

现在你想用

contents.whatWeAreLookingFor

访问值,但是这个属性对这些对象来说是未定义的。所以你的控制台记录了undefined。你必须使用以下方式访问值:

contents.AlmostThere.whatWeAreLookingFor

所以你得到了AlmostThere对象并选择属性whatWeAreLookingFor

如果你使用jquery,你应该使用:

$.each(jsonData.TheArray, function() {
     console.log(contents.AlmostThere.whatWeAreLookingFor + '!');
});

API:http://api.jquery.com/jquery.each/

0
0 Comments

你忘记访问了 AlmostThere

  jsonData.TheArray[i].AlmostThere.whatWeAreLookingFor


for (var i = 0; i < jsonData.TheArray.length; i++) {
    console.log(jsonData.TheArray[i].AlmostThere.whatWeAreLookingFor);
}

0