[英]Javascript - Error when accessing an associative array value
I have an array, locations:我有一个数组,位置:
{
"locations":[
"{\"location_id\":\"1\",\"location_name\":\"Main Office\"}",
"{\"location_id\":\"6\",\"location_name\":\"Secondary\"}"
]
}
I am trying to loop through this array to display the location id/name, but keep getting undefined errors.我试图遍历此数组以显示位置 ID/名称,但不断收到未定义的错误。
for (var i = 0; i < locations.length; ++i) {
alert(locations[i].location_id);
}
If I do alert(locations[i])
, I can see the individual array contents for that index, but seemingly have no way go any further.如果我执行alert(locations[i])
,我可以看到该索引的各个数组内容,但似乎无法进一步查看 go 。
I feel like I'm missing something incredibly simple and would appreciate any help.我觉得我错过了一些非常简单的东西,非常感谢任何帮助。 Everything I've read suggests I should just be able to get the value of the array by using the for [i] loop.我读过的所有内容都表明我应该能够通过使用 for [i] 循环来获取数组的值。
I will list all the noticeable problems in your query我将列出您查询中所有明显的问题
String
hence the locations[i].location_id
would not work as the "dot" operator expects an object “locations”数组的所有元素都是String
类型,因此locations[i].location_id
将不起作用,因为“点”运算符期望 objectSuggestions建议
let locations = [
{ location_id: 1, location_name: 'Main office'},
{ location_id: 2, location_name: 'any name' },
];
define it like:像这样定义它:
let locations = [
{ location_id: 1, location_name: 'Main office'},
{ location_id: 2, location_name: 'any name' },
];
locations.forEach(location => {
alert(location.location_id);
});
Or if your data is in json format:或者,如果您的数据是 json 格式:
let json = '{ "locations": [ { "location_id": 3, "location_name": "Name" } ]}';
const data = JSON.parse(json);
data.locations.forEach(location => {
console.log(location.location_id);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.