我有许多国家和人口。我如何才能撤回所有国家的人口数量?
[
{ name: 'Poland', population: 42 000 000},
{ name: 'Belarus', population: 9 500 000},
{ name: 'Moldova', population: 3 500 000},
{ name: 'Switzerland', population: 8 400 000}
]
function calculateAverageCountryPopulation(countries) {
}
数组元素的总和并不困难。但是我不知道该怎么做。
var arr = [3, 2, 5, 6];
function arraySum(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum += array[i];
}
console.log(sum);
}
arraySum(arr);
答案 0 :(得分:0)
function calculateAverageCountryPopulation(countries) {
return countries.map(x => x.population).reduce((acc, y) => acc + y)
}
答案 1 :(得分:0)
使用减少和除法。
const data = [
{ name: 'Poland', population: 42000000},
{ name: 'Belarus', population: 9500000},
{ name: 'Moldova', population: 3500000},
{ name: 'Switzerland', population: 8400000}
]
const calculateAverageCountryPopulation = (countries) => countries.reduce((a,{ population: p}) => a+=p,0)/countries.length;
console.log(calculateAverageCountryPopulation(data));