我目前正在努力做一些相当简单的事情。我只想打印出该数组中每个对象的特定键值。我很感激任何指针!
var countries = [
{
'country name': 'Australia',
'national emblem': 'blue red white',
'hemisphere': 'southern',
'population': 24130000
},
{
'country name': 'United States',
'national emblem': 'blue red white',
'hemisphere': 'northern',
'population': 323000000
},
{
'country name': 'Uzbekistan',
'national emblem': 'blue green red white',
'hemisphere': 'northern',
'population': 31850000
}
];
function getCountryprops(countries){
for(var oneCountry in countries){
for(var propName in oneCountry){
console.log(oneCountry[propName]['country name'], oneCountry[propName]['population']);
}
}
}

所以我想最终打印出[[' Australia' 24130000],[' United States' 323000000],[' Uzbekistan',31850000] ]
答案 0 :(得分:1)
在countries
数组上使用for...in
时,oneCountry
变量是当前国家/地区的索引。要获取国家/地区,您需要在countries
数组中使用括号表示法:
var countries = [{"country name":"Australia","national emblem":"blue red white","hemisphere":"southern","population":24130000},{"country name":"United States","national emblem":"blue red white","hemisphere":"northern","population":323000000},{"country name":"Uzbekistan","national emblem":"blue green red white","hemisphere":"northern","population":31850000}];
function getCountryprops(countries){
for(var oneCountry in countries){
console.log(countries[oneCountry]['country name'], countries[oneCountry]['population']);
}
}
getCountryprops(countries);
另一种选择是使用for...of
直接获取国家/地区的价值:
var countries = [{"country name":"Australia","national emblem":"blue red white","hemisphere":"southern","population":24130000},{"country name":"United States","national emblem":"blue red white","hemisphere":"northern","population":323000000},{"country name":"Uzbekistan","national emblem":"blue green red white","hemisphere":"northern","population":31850000}];
function getCountryprops(countries){
for(var oneCountry of countries){
console.log(oneCountry['country name'], oneCountry['population']);
}
}
getCountryprops(countries);