reduce
方法是 JavaScript 中的一个数组方法,它对数组中的每个元素执行一个由你提供的 reducer
回调函数(升序执行),将其结果汇总为单个返回值。
array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
- callback: 一个在每个元素上执行的函数,包含四个参数:
- accumulator (累加器): 上一次调用回调时返回的累积值,或者是提供的初始值(如果提供了的话)。
- currentValue: 数组中正在处理的元素。
- index (可选): 当前元素的索引。如果提供了初始值,则起始于 0,否则从 1 开始。
- array (可选): 调用
reduce
的数组本身。
- initialValue (可选): 作为第一次调用回调函数的第一个参数的初始值。如果没有提供初始值,则将使用数组中的第一个元素作为初始值,并从第二个元素开始处理。
实例:
求和:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0); // 从0开始累加
console.log(sum); // 输出: 15
求平均值:
const numbers = [1, 2, 3, 4, 5];
const average = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0) / numbers.length;
console.log(average); // 输出: 3
合并数组:
const arrays = [[1, 2], [3, 4], [5]];
const flattened = arrays.reduce((accumulator, currentValue) => {
return accumulator.concat(currentValue);
}, []);
console.log(flattened); // 输出: [1, 2, 3, 4, 5]
对象累加:
const people = [
{ name: 'John', age: 20 },
{ name: 'Jane', age: 18 },
{ name: 'Smith', age: 22 }
];
const totalAge = people.reduce((accumulator, { age }) => {
return accumulator + age;
}, 0);
console.log(totalAge); // 输出: 60
过滤并累加:
const numbers = [1, 2, 3, 4, 5];
const sumEven = numbers.reduce((accumulator, currentValue) => {
if (currentValue % 2 === 0) {
return accumulator + currentValue;
}
return accumulator;
}, 0);
console.log(sumEven); // 输出: 6 (2 + 4)
reduce
方法非常强大,可以用于多种场景,从简单的累加到复杂的数据转换。它允许你将数组中的元素通过某种方式“压缩”成单个值。