任何人都可以提示我如何使用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){
}
}
也许您会感到困惑,因为forEach
回调中的参数名称不能正确表示它们的实际含义。
.forEach
回调函数的第一个参数是您当前对其进行迭代的元素。在您的情况下,它是您当前在currencies
阵列中使用的对象。它不是id
您命名的样子。
.forEach
回调中的第二个参数是索引,但是,您不需要它,因为您所需要的只是对象(这是第一个参数)
因此,如果第一个参数是对象,则可以在每次迭代中使用点符号访问其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"}];
const populateCurrencies = (currencies) => {
currencies.forEach(function(obj) {
console.log(obj.name, obj.id);
});
}
populateCurrencies(currencies)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句