所以我以JSON格式获得了一个机场列表,就像这样:
下面是数组中的一些条目:
var airportData = {
"00AK": {
"icao": "00AK",
"iata": "",
"name": "Lowell Field",
"city": "Anchor Point",
"state": "Alaska",
"country": "US",
"elevation": 450,
"lat": 59.94919968,
"lon": -151.695999146,
"tz": "America\/Anchorage"
},
"00AL": {
"icao": "00AL",
"iata": "",
"name": "Epps Airpark",
"city": "Harvest",
"state": "Alabama",
"country": "US",
"elevation": 820,
"lat": 34.8647994995,
"lon": -86.7703018188,
"tz": "America\/Chicago"
},
"00AZ": {
"icao": "00AZ",
"iata": "",
"name": "Cordes Airport",
"city": "Cordes",
"state": "Arizona",
"country": "US",
"elevation": 3810,
"lat": 34.3055992126,
"lon": -112.1650009155,
"tz": "America\/Phoenix"
}
"00CA": {
"icao": "00CA",
"iata": "",
"name": "Goldstone \/Gts\/ Airport",
"city": "Barstow",
"state": "California",
"country": "US",
"elevation": 3038,
"lat": 35.3504981995,
"lon": -116.888000488,
"tz": "America\/Los_Angeles"
},
"00CO": {
"icao": "00CO",
"iata": "",
"name": "Cass Field",
"city": "Briggsdale",
"state": "Colorado",
"country": "US",
"elevation": 4830,
"lat": 40.6222000122,
"lon": -104.34400177,
"tz": "America\/Denver"
},
"00FA": {
"icao": "00FA",
"iata": "",
"name": "Grass Patch Airport",
"city": "Bushnell",
"state": "Florida",
"country": "US",
"elevation": 53,
"lat": 28.6455001831,
"lon": -82.21900177,
"tz": "America\/New_York"
}
}
00AK,00AL,00AZ等对象中的每一个都代表某个机场。现在,我要做的就是获取每个对象的属性。
这是我尝试获取“名称”属性的方法:
for (var airport in airportData)
{
var opt = document.createElement("option");
opt.innerHTML = airport.name + " (" + airport.icao + ")";
airport_list.appendChild(opt);
console.log(airport.name);
}
但是airport.name始终返回“未定义”。我看过许多其他示例,但是它们的结构都不同于我正在看的示例。
所以我的问题是,应该如何更改代码中的“名称”属性?
答案 0 :(得分:1)
在foor循环中,变量airport
将遍历airportData
的键。如果要遍历这些值,则需要通过airportData[airport]
访问它们。改进后的代码如下所示:
for (var key in airportData)
{
var airport = airportData[key];
var opt = document.createElement("option");
opt.innerHTML = airport.name + " (" + airport.icao + ")";
airport_list.appendChild(opt);
console.log(airport.name);
}