reduce()
是 JavaScript 数组中的一个高阶函数,它用于对数组中的所有元素执行一个给定的累加器函数,并最终返回一个单一的值。reduce()
可以用于数组的求和、对象合并、数组去重等多种操作。
语法:
array.reduce((accumulator, currentValue, currentIndex, array) => {
// 函数体
}, initialValue);
参数:
-
callback 函数:
accumulator
:累加器,存储上一次调用callback
时返回的值,或是初始值。currentValue
:当前正在处理的数组元素。currentIndex
:当前元素的索引(可选)。array
:调用reduce()
的数组本身(可选)。
-
initialValue(可选):累加器的初始值。如果没有提供
initialValue
,则数组的第一个元素将作为累加器的初始值,currentValue
从数组的第二个元素开始。
工作原理:
reduce()
依次对数组中的每个元素调用callback
函数,使用上一次调用callback
返回的值作为accumulator
,结合当前元素的值来计算出一个新的值,最终累加成一个单一的输出。
示例 1:数组求和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // 输出 15
解释:
initialValue
为0
,accumulator
的初始值为0
,之后逐步将每个数组元素累加。
示例 2:数组最大值
const numbers = [1, 5, 3, 9, 2];
const max = numbers.reduce((accumulator, currentValue) => {
return currentValue > accumulator ? currentValue : accumulator;
}, numbers[0]);
console.log(max); // 输出 9
解释:
- 使用
reduce()
找出数组中的最大值,accumulator
开始为数组的第一个值,并逐步与当前值比较,保留更大的值。
示例 3:将二维数组拍平
const array = [[1, 2], [3, 4], [5, 6]];
const flatArray = array.reduce((accumulator, currentValue) => {
return accumulator.concat(currentValue);
}, []);
console.log(flatArray); // 输出 [1, 2, 3, 4, 5, 6]
解释:
reduce()
将二维数组扁平化,将每个子数组连接到accumulator
中。
示例 4:统计数组中元素出现的次数
const fruits = ['apple', 'banana', 'orange', 'apple', 'orange', 'banana', 'banana'];
const count = fruits.reduce((accumulator, fruit) => {
accumulator[fruit] = (accumulator[fruit] || 0) + 1;
return accumulator;
}, {});
console.log(count); // 输出 { apple: 2, banana: 3, orange: 2 }
解释:
- 通过
reduce()
累积每个元素的出现次数,accumulator
是一个对象,用于存储每个水果的数量。
示例 5:对象数组求和
假设我们有一个对象数组,想对其中某个属性进行求和:
const products = [
{ name: 'Laptop', price: 1000 },
{ name: 'Phone', price: 500 },
{ name: 'Tablet', price: 750 }
];
const total = products.reduce((accumulator, product) => {
return accumulator + product.price;
}, 0);
console.log(total); // 输出 2250
解释:
- 对象数组中的
price
属性相加,得到总价格。
总结:
reduce()
是一个非常强大且灵活的数组方法,它能够通过不断累计处理数组元素,生成单一的结果。根据不同的初始值和处理逻辑,reduce()
可以用于各种任务,如求和、去重、分组、累积等等。