gpt4 book ai didi

javascript - 从此对象中选择特定属性值时遇到问题

转载 作者:行者123 更新时间:2023-12-01 02:23:58 24 4
gpt4 key购买 nike

我目前正在努力做一些相当简单的事情。我只想打印出该数组中每个对象的特定键值。如果有任何指点,我将不胜感激!

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']);
}
}
}

所以我想最终打印出 [['澳大利亚', 24130000],['美国', 323000000],['乌兹别克斯坦', 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直接获取国家的值(value):

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com