reduce 方法将一个累加器及阵列中每项元素(由左至右)传入回呼函式,将阵列化为单一值。

const people = [
{ name: "Zoe", age: 28 },
{ name: "Liam", age: 32 },
{ name: "Emma", age: 26 },
{ name: "Noah", age: 30 },
{ name: "Olivia", age: 24 },
];

// 2. 使用 reduce 方法计算并返回所有人的平均年龄。
const MapNewage = people.map((age) => age.age);
console.log("Map重组只含Age属性的阵列:", MapNewage);

let average = MapNewage.reduce((accumulator, currentValue) => {
return accumulator + currentValue / MapNewage.length;
}, 0);
console.log("reduce平均值:", average);

// 4. 找出阵列中最年轻的人
// 使用 reduce 方法从人员阵列中找出最年轻的人。
const youngMan = MapNewage.reduce((initial, big) => {
//(初始值,比较值)
if (big < initial) {
return big;
}
return initial;
});
console.log("最年轻的人:", youngMan, "岁");

// reduce 的基础语法
// accumulator:经由个别 currentValue 加总的累计值
// currentValue:Array 的个别 item
// currentIndex:Array item 的索引
// array:呼叫该 Array method 的阵列
// initialValue:预设值,放在 function 的最后方,非必填