谁能提示我如何使用forEach方法迭代货币数组以获取对象的ID和名称。
const currencies = [{
id: 'USD', name: 'US Dollars'
}, {
id: 'UGX', name: 'Ugandan Shillings'
}, {
id: 'KES', name: 'Kenyan Shillings'
}, {
id: 'GHS', name: 'Ghanian Cedi'
}, {
id: 'ZAR', name: 'South African Rand'
}];
var populateCurrencies = (currencies)=>{
currencies.forEach(function(id,name){
}
}
答案 0 :(得分:2)
也许您会感到困惑,因为forEach
回调中的参数名称实际上是错误的。
.forEach
回调函数的第一个参数是当前要迭代的 element 。在您的情况下,它是货币数组中当前位于的对象。它不是您命名的id
。
.forEach
回调中的第二个参数是索引,但是,您不需要它,因为您所需要的只是对象(这是第一个参数)
因此,如果第一个参数是对象,则可以在每次迭代中使用dot notation访问其name
和id
属性。
请参见以下示例:
const currencies = [{id:"USD",name:"US Dollars"},{id:"UGX",name:"Ugandan Shillings"},{id:"KES",name:"Kenyan Shillings"},{id:"GHS",name:"Ghanian Cedi"},{id:"ZAR",name:"South African Rand"}];
var populateCurrencies = (currencies) => {
currencies.forEach(function(obj) {
console.log(obj.name, obj.id);
});
}
populateCurrencies(currencies)
答案 1 :(得分:1)
extract properties
传递给foreach迭代器的项目中:
const currencies = [{
id: 'USD', name: 'US Dollars'
}, {
id: 'UGX', name: 'Ugandan Shillings'
}, {
id: 'KES', name: 'Kenyan Shillings'
}, {
id: 'GHS', name: 'Ghanian Cedi'
}, {
id: 'ZAR', name: 'South African Rand'
}];
currencies.forEach(function({id,name}){
console.log(id,name);
})
答案 2 :(得分:0)
const currencies = [{
id: 'USD', name: 'US Dollars'
}, {
id: 'UGX', name: 'Ugandan Shillings'
}, {
id: 'KES', name: 'Kenyan Shillings'
}, {
id: 'GHS', name: 'Ghanian Cedi'
}, {
id: 'ZAR', name: 'South African Rand'
}];
currencies.forEach(currency =>
console.log(currency.id + " : " + currency.name)
)