Roshin's blog Roshin's blog
首页
  • 《数据结构与算法》笔记
  • 手写代码
  • 实用方法
  • 文档教程
  • 面试集锦
  • 分类
  • 标签
  • 归档
  • 个人介绍
  • 关于博客
  • 友情链接
GitHub (opens new window)

Roshin

如果你只做自己能力范围之内的事情,就永远没法进步。
首页
  • 《数据结构与算法》笔记
  • 手写代码
  • 实用方法
  • 文档教程
  • 面试集锦
  • 分类
  • 标签
  • 归档
  • 个人介绍
  • 关于博客
  • 友情链接
GitHub (opens new window)
  • 手写代码

    • Array.prototype.map()
    • Array.prototype.reduce()
      • Array.prototype.reduce()
      • 语法
      • 参数
      • 返回值
      • 示例
      • 手写实现
    • Array.prototype.flat()
    • instanceof 运算符
  • 实用方法

  • JavaScript
  • 手写代码
roshin
2021-04-14

Array.prototype.reduce()

Array.prototype.reduce() #

reduce() 方法接收一个函数作为累加器,从左到右依次遍历数组中的每个值,最终计算为一个值。

语法 #

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
1

参数 #

  • callback: 数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,包含四个参数:
    • accumulator: 累计器累计回调的返回值,它是上一次调用回调时返回的累积值,或 initialValue
    • currentValue: 正在处理的当前元素
    • index(可选): 正在处理的当前元素的索引。如果提供了 initialValue,则起始索引号为 0,否则从索引 1 起始
    • array(可选): 调用 reduce() 的数组
  • initialValue(可选): 作为第一次调用 callback 函数时的第一个参数的值。如果没有提供初始值,则将使用数组中的第一个元素。在没有初始值的空数组上调用 reduce 将报错

返回值 #

函数累计处理的结果。

示例 #

const arr = [0, 1, 2, 3];
const sum = arr.reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);

const sum2 = arr.reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 10);

console.log(sum); // 6
console.log(sum2); // 16
1
2
3
4
5
6
7
8
9
10
11

手写实现 #

Array.prototype.myReduce = function reduce(callback, initialValue) {
  // 首先判断传入的第一个参数是否为函数, 如果不是则抛出错误
  if (Object.prototype.toString.call(callback) !== '[object Function]') {
    throw '第一个参数必须是一个函数';
  }

  const array = this; // 拿到当前数组
  const index = initialValue === undefined ? 1 : 0; // 如果存在初始值,索引从 1 开始,否则从 0 开始
  let accumulator = initialValue || array[0]; // 拿到初始值

  // 遍历, 调用传入的函数, 并将返回值保存在 result 中,注意这里将 this 指向改为 thisArg
  for (let i = index; i < array.length; i++) {
    accumulator = callback(accumulator, array[i], i, array);
  }

  return accumulator;
};

const arr = [0, 1, 2, 3];
const sum = arr.reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);

const sum2 = arr.reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 10);

console.log(sum); // 6
console.log(sum2); // 16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
编辑 (opens new window)
上次更新: 2021-06-23 08:43:55
Array.prototype.map()
Array.prototype.flat()

← Array.prototype.map() Array.prototype.flat()→

最近更新
01
函数柯里化
04-15
02
Array.prototype.flat()
04-14
03
instanceof 运算符
04-13
更多文章>
Theme by Vdoing Copyright © 2021-present Roshin | MIT License | 粤ICP备18116277号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式