JS之数组中的reduce方法

文章目录

      • 基本语法:
      • [callbackFn 的参数:](#callbackFn 的参数:)
      • 例子
        • [1. 数组求和](#1. 数组求和)
        • [2. 数组求积](#2. 数组求积)
        • [3. 扁平化数组](#3. 扁平化数组)
        • [4. 数组元素计数](#4. 数组元素计数)
        • [5. 使用对象解构和展开运算符合并数组中的对象](#5. 使用对象解构和展开运算符合并数组中的对象)
        • [6. 求最大值和最小值](#6. 求最大值和最小值)
      • 函数组合
      • [异步操作中的 `reduce`](#异步操作中的 reduce)
      • 总结

reduce 是 JavaScript 中 Array 对象的一个方法,非常强大且多用途。它可以对数组中的每个元素执行一个提供的回调函数,并且将结果汇总为一个单一的输出值。

基本语法:

javascript 复制代码
array.reduce(callbackFn, initialValue);
  • callbackFn: 一个回调函数,用于计算的每一步,它接收四个参数。
  • initialValue (可选): 作为第一次调用 callbackFn 时第一个参数的值。如果没有提供 initialValue,则 reduce 会从数组的第二个元素开始执行 callbackFn,且 accumulator 会被初始化为数组的第一个元素。

callbackFn 的参数:

javascript 复制代码
function callbackFn(accumulator, currentValue, currentIndex, array) {
  // ...
}
  • accumulator: 累计器,用来累计回调的返回值,是累计的结果。
  • currentValue: 数组中正在处理的当前元素。
  • currentIndex (可选): 数组中正在处理的当前元素的索引。
  • array (可选): 调用 reduce 的数组。

例子

1. 数组求和

计算数组中所有元素的和:

javascript 复制代码
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 输出: 15
2. 数组求积

计算数组中所有元素的积:

javascript 复制代码
const numbers = [1, 2, 3, 4, 5];
const product = numbers.reduce((accumulator, currentValue) => accumulator * currentValue, 1);
console.log(product); // 输出: 120
3. 扁平化数组

将一个二维数组扁平化为一维数组:

javascript 复制代码
const arrays = [[1, 2], [3, 4], [5, 6]];
const flattened = arrays.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
console.log(flattened); // 输出: [1, 2, 3, 4, 5, 6]
4. 数组元素计数

统计数组中每个元素的出现次数:

javascript 复制代码
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const fruitCount = fruits.reduce((accumulator, currentValue) => {
  if (accumulator[currentValue]) {
    accumulator[currentValue]++;
  } else {
    accumulator[currentValue] = 1;
  }
  return accumulator;
}, {});
console.log(fruitCount); // 输出: { apple: 3, banana: 2, orange: 1 }
5. 使用对象解构和展开运算符合并数组中的对象

假设你有一个包含了一些对象的数组,现在你想合并这些对象:

javascript 复制代码
const objects = [{ a: 1 }, { b: 2 }, { c: 3 }];
const mergedObject = objects.reduce((accumulator, currentValue) => {
  return { ...accumulator, ...currentValue };
}, {});
console.log(mergedObject); // 输出: { a: 1, b: 2, c: 3 }
6. 求最大值和最小值

在数组中找出最大值和最小值:

javascript 复制代码
const numbers = [1, 2, 3, 4, 5];

// 最大值
const max = numbers.reduce((accumulator, currentValue) => Math.max(accumulator, currentValue));
console.log(max); // 输出: 5

// 最小值
const min = numbers.reduce((accumulator, currentValue) => Math.min(accumulator, currentValue));
console.log(min); // 输出: 1

函数组合

通过 reduce 实现函数组合(compose pattern):

javascript 复制代码
const compose = (...funcs) => initialValue =>
  funcs.reduceRight((accumulator, func) => func(accumulator), initialValue);

// 示例函数
const add5 = x => x + 5;
const multiply = x => x * 2;

const composedFunc = compose(multiply, add5);
console.log(composedFunc(10)); // 输出: 30 (首先 add5(10) 得到 15,然后 multiply(15) 得到 30)

异步操作中的 reduce

虽然 reduce 本身是同步的,但你也可以在异步场景中结合 async/await 使用:

javascript 复制代码
const urls = ['url1', 'url2', 'url3'];

async function fetchUrl(url) {
  // 模拟异步 fetch 操作
  return new Promise((resolve) => setTimeout(() => resolve(`Data from ${url}`), 1000));
}

async function fetchData() {
  const results = await urls.reduce(async (accumulatorPromise, url) => {
    const accumulator = await accumulatorPromise;
    const data = await fetchUrl(url);
    accumulator.push(data);
    return accumulator;
  }, Promise.resolve([]));

  console.log(results); // ["Data from url1", "Data from url2", "Data from url3"]
}

fetchData();

总结

reduce 是一个功能非常强大的高阶函数,可以用来解决各种数组操作和数据处理问题。通过理解它的工作原理和灵活运用 callback 函数,你可以编写出简洁高效且具有高度表达力的代码。

相关推荐
猫猫不是喵喵.7 分钟前
Java开发高频面试题汇总(通俗易懂版)
java·开发语言·java高频面试
k4m7v2pz14 分钟前
用 rust-verb-shell 重写进程管理:从 game.sh 到 .rvs 的迁移实录
开发语言·后端·rust
2603_9658966216 分钟前
JavaScript 对象零基础详解|属性、方法、遍历、增删改查
开发语言·javascript·ecmascript
dear_bi_MyOnly21 分钟前
数组字符串深度解析:从入门到卡牌实战
开发语言·c++·学习
天道kabuto25 分钟前
踩坑实录:JS Map迭代器为什么“用完即焚”?兼谈技术知识沉淀
前端
正在走向自律25 分钟前
从 Python 基础到大模型落地:读《深入浅出 Python 人工智能》,吃透 AI 工程化 CRUD 实战
开发语言·人工智能·python·机器学习·知识脉络
字节跳动开源29 分钟前
VisActor全新图可视化开源项目:VGraph
前端·设计模式·开源
打呵欠的猫31 分钟前
前端接口超时从 15s 改到动态值后,用户投诉降了 60%——AI 帮我分析出的方案
前端·ai编程
岁月宁静31 分钟前
二、《从零手撸 Agent》 — 聊聊 LLM 的失忆真相
前端·python·agent
郭邯38 分钟前
用纯前端实现一个代码压缩美化工具,我踩了这三个坑
前端