js中reduce函数的用法

js中reduce函数的用法
最新回答
碍人

2022-05-15 14:09:16

reduce 是 JavaScript 中用于累积数组元素并返回单一值的强大方法。其核心机制是通过回调函数逐步处理数组元素,并将结果存储在累积器中。以下是详细说明和典型用例:

基本语法const result = array.reduce(callback, initialValue);
  • array:待处理的数组。
  • callback:处理逻辑的函数,接收以下参数:

    accumulator:累积结果,每次迭代后更新。

    currentValue:当前处理的数组元素。

    (可选)currentIndexarray 本身。

  • initialValue(可选):累积器的初始值。若省略,默认使用数组的第一个元素,并从第二个元素开始迭代。
关键注意事项
  1. 初始值的重要性

    提供 initialValue 可避免空数组报错(如 [].reduce(() => {}, 0) 合法,但省略初始值会抛出错误)。

    影响第一次迭代的 accumulator 值(例如求和时设为 0 而非数组首元素)。

  2. 回调函数的返回值每次回调必须返回更新后的 accumulator,否则后续迭代会使用 undefined。

常见用例1. 求和const sum = [1, 2, 3].reduce((acc, val) => acc + val, 0); // 6
  • 初始值设为 0,确保正确处理空数组。
2. 求平均值const avg = [10, 20, 30].reduce((acc, val, idx, arr) => { acc += val; return idx === arr.length - 1 ? acc / arr.length : acc;}, 0); // 20
  • 在最后一次迭代时计算平均值。
3. 连接数组元素const str = ['a', 'b', 'c'].reduce((acc, val) => acc + val, ''); // "abc"
  • 初始值为空字符串,避免开头出现 undefined。
4. 过滤元素const evens = [1, 2, 3, 4].reduce((acc, val) => { if (val % 2 === 0) acc.push(val); return acc;}, []); // [2, 4]
  • 初始值为空数组,通过条件筛选元素。
5. 分组对象const people = [ { name: 'Alice', age: 21 }, { name: 'Bob', age: 25 }];const grouped = people.reduce((acc, person) => { const key = person.age >= 22 ? 'adult' : 'child'; acc[key] = (acc[key] || []).concat(person); return acc;}, {});// { child: [{ name: 'Alice', age: 21 }], adult: [{ name: 'Bob', age: 25 }] }
  • 动态创建分组键,并累积到对象中。
高级技巧
  • 链式操作:结合 map 或 filter 预处理数据后再累积。const total = [1, 2, 3] .filter(x => x > 1) .reduce((acc, val) => acc + val, 0); // 5
  • 扁平化数组:const flat = [[1, 2], [3, 4]].reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4]
总结

reduce 的灵活性使其适用于多种场景,但需注意:

  • 始终提供初始值以避免意外行为。
  • 明确回调的返回值,确保累积逻辑正确。
  • 复杂操作可拆分为多个步骤(如先过滤再累积),提升可读性。

通过合理使用 reduce,可以简洁高效地实现数据转换和计算。