How to iterate through an object stored in an array list
本问题已经有最佳答案,请猛点这里访问。
任何人都能告诉我如何使用foreach方法迭代货币数组以获取对象的ID和名称吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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){ } } |
也许你会感到困惑,因为你的
因此,如果第一个参数是对象,则可以使用点表示法在每次迭代时访问其
见下例:
1 2 3 4 5 6 7 8 9 | 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) |
向传递给foreach迭代器的项的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); }) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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) ) |