【js】 数组 reduce 学习记录

64 阅读2分钟

reduce 是 JavaScript 中数组方法之一,它对数组中的每个元素执行一个提供的函数(升序执行),将其结果累积为单个返回值。这个方法非常强大,可以用于数组的聚合、过滤、映射等操作。以下是对 reduce 方法的详细解释和使用示例。

语法

array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue);

参数

  • callback: 在数组的每个元素上调用的函数,接受四个参数:
    • accumulator: 累积器,累积回调的返回值;它是上一次调用回调时返回的累积值。
    • currentValue: 当前数组元素。
    • currentIndex(可选): 当前元素的索引。
    • array(可选): 调用 reduce 的数组。
  • initialValue(可选): 作为第一次调用 callback 函数时的第一个参数的值。如果没有提供 initialValue,则将使用数组中的第一个元素。

示例

1. 求数组元素和

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 输出: 15

2. 求数组元素积

const numbers = [1, 2, 3, 4, 5];
const product = numbers.reduce((accumulator, currentValue) => accumulator * currentValue, 1);
console.log(product); // 输出: 120

3. 计算数组中每个元素出现的次数

const fruits = ['apple', 'banana', 'orange', 'apple', 'orange', 'banana', 'banana'];
const count = fruits.reduce((accumulator, currentValue) => {
    accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
    return accumulator;
}, {});
console.log(count); // 输出: { apple: 2, banana: 3, orange: 2 }

4. 将二维数组转为一维数组

const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flatArray = nestedArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
console.log(flatArray); // 输出: [1, 2, 3, 4, 5, 6]

5. 将数组转为对象

const people = [  { id: 1, name: 'Alice' },  { id: 2, name: 'Bob' },  { id: 3, name: 'Charlie' }];
const peopleObj = people.reduce((accumulator, currentValue) => {
    accumulator[currentValue.id] = currentValue;
    return accumulator;
}, {});
console.log(peopleObj);
// 输出: 
// {
//   1: { id: 1, name: 'Alice' },
//   2: { id: 2, name: 'Bob' },
//   3: { id: 3, name: 'Charlie' }
// }

详细解释

  1. 累积器(Accumulator):

    • 在每次回调执行时,累积器 accumulator 会被更新为回调函数的返回值。
    • 初始的 accumulatorinitialValue,如果未提供 initialValue,则默认为数组的第一个元素。
  2. 回调函数:

    • 在回调函数中,可以对 accumulatorcurrentValue 进行各种操作,最后返回新的 accumulator
  3. 初始值(Initial Value):

    • 提供 initialValue 可以让 reduce 方法从指定的初始值开始累积,如果没有提供则从数组的第一个元素开始。

总结

reduce 方法非常灵活且强大,可以用于许多场景如数组求和、数组扁平化、统计元素频率等。掌握 reduce 的使用可以让你在处理数组时写出更简洁和高效的代码。