reduce 方法用途
数组 reduce 方法的使用场景和实现原理
问题
数组中的 reduce 方法有什么用途?
解答
reduce() 是数组的高阶方法,用于对数组元素进行累积操作,最终返回一个单一的值。
语法
array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
参数说明:
accumulator:累积值(上一次回调的返回值或初始值)currentValue:当前元素currentIndex:当前索引array:原始数组initialValue:初始值(可选)
执行过程
- 如果提供了初始值,则将其作为累积值;否则使用数组的第一个元素作为初始累积值
- 对数组中的每个元素调用回调函数,传递累积值、当前值、当前索引和原始数组
- 回调函数的返回值作为下一次调用的累积值
- 返回最后一次回调函数的返回值
常见用途
求和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, cur) => acc + cur, 0);
console.log(sum); // 15
求平均值
const numbers = [1, 2, 3, 4, 5];
const average = numbers.reduce((acc, cur, index, array) => {
acc += cur;
return index === array.length - 1 ? acc / array.length : acc;
}, 0);
console.log(average); // 3
查找最大值
const numbers = [5, 2, 8, 1, 9];
const max = numbers.reduce((acc, cur) => Math.max(acc, cur));
console.log(max); // 9
数组去重
const numbers = [1, 2, 2, 3, 3, 4];
const unique = numbers.reduce((acc, cur) => {
if (!acc.includes(cur)) {
acc.push(cur);
}
return acc;
}, []);
console.log(unique); // [1, 2, 3, 4]
对象属性统计
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const count = fruits.reduce((acc, cur) => {
acc[cur] = (acc[cur] || 0) + 1;
return acc;
}, {});
console.log(count); // { apple: 3, banana: 2, orange: 1 }
关键点
reduce将数组转换为单一值,适用于累积计算场景- 建议始终提供初始值,避免空数组报错
- 回调函数必须返回累积值,否则下一次迭代会得到
undefined - 可以用于求和、求平均、查找极值、数组转对象等多种场景
目录