循环遍历JSON数组时显示"undefined"结果。
循环遍历JSON数组时显示"undefined"结果。
这个问题已经有了答案:
我有一个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日
如果你用你自己的方式循环数组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 + '!'); });