我目前正在努力做一些简单明了的事情。我只想为该数组中的每个对象打印出特定的键值。我将不胜感激!
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]]
最佳答案
在for...in
数组上使用countries
时,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);
关于javascript - 无法从此对象选择特定的属性值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48967219/