Array.reduce() 是JavaScript中用于将数组元素累积计算为单个值的高阶函数,其核心作用是对数组中的每个元素执行一个累加器函数,最终返回累积结果。以下是详细用法和示例:
一、基本语法
array.reduce((accumulator, currentValue, currentIndex, array) => {
// 累加逻辑
return newAccumulator;
}, initialValue);
- 参数说明:
- accumulator :累加器,保存上一次回调的结果。
- currentValue :当前处理的数组元素。
- currentIndex (可选):当前元素的索引。
- array (可选):原数组。
- initialValue (可选):累加器的初始值。
二、核心用法示例
1. 数组求和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
- 初始值 0 传入后,累加过程为: 0 + 1 = 1 → 1 + 2 = 3 → 3 + 3 = 6 → 6 + 4 = 10 → 10 + 5 = 15 。
2. 对象数组分组
const people = [
{ name: 'A', age: 20 },
{ name: 'B', age: 25 },
{ name: 'C', age: 30 },
{ name: 'D', age: 20 }
];
const groupedByAge = people.reduce((acc, person) => {
// 以age为键,将同年龄的人分组
if (!acc[person.age]) {
acc[person.age] = [];
}
acc[person.age].push(person);
return acc;
}, {});
console.log(groupedByAge);
/* 输出:
{
"20": [{ name: 'A', age: 20 }, { name: 'D', age: 20 }],
"25": [{ name: 'B', age: 25 }],
"30": [{ name: 'C', age: 30 }]
}
*/
3. 计算对象属性最大值
const products = [
{ price: 100 },
{ price: 150 },
{ price: 80 },
{ price: 200 }
];
const maxPrice = products.reduce((max, product) => {
return product.price > max ? product.price : max;
}, 0);
console.log(maxPrice); // 200
三、初始值(initialValue)的作用
1. 提供初始累加值
- 若不传入 initialValue , reduce 会从数组第一个元素开始,将前两个元素作为初始 accumulator 和 currentValue 。
- 传入 initialValue 时,会从数组第一个元素开始,将 initialValue 作为初始 accumulator 。
2. 空数组的处理
- 数组为空且未传 initialValue 时,调用 reduce 会报错(无初始值)。
- 数组为空但传了 initialValue 时,直接返回 initialValue :
const emptyArray = [];
const result = emptyArray.reduce((acc, val) => acc + val, 100);
console.log(result); // 100(直接返回初始值)