例如,我们有一个包含成绩列表的数组,我们需要求所有成绩的平均值:
const scores = [85, 90, 76, 92, 88];
const total = scores.reduce((acc, score) => acc + score, 0);
const average = total / scores.length;
console.log(average); // 输出:86.2
如果需要返回每个分数及其下标位置,可以将reduce方法替换为以下代码:
const scores = [85, 90, 76, 92, 88];
const results = scores.map((score, index) => {
return {
score,
index
};
}).reduce((acc, data) => {
acc[data.index] = data.score;
return acc;
}, []);
console.log(results); // 输出:[85, 90, 76, 92, 88]
例如,我们有一个包含成绩列表的数组,我们需要抽取前三个成绩:
const scores = [85, 90, 76, 92, 88];
const topThreeScores = scores.reduce((acc, score, index) => {
if (index < 3) {
acc.push(score);
}
return acc;
}, []);
console.log(topThreeScores); // 返回:[85, 90, 76]
使用Array.slice()方法,可以替换上面的代码:
const scores = [85, 90, 76, 92, 88];
const topThreeScores = scores.slice(0, 3);
console.log(topThreeScores); // 返回:[85, 90, 76]