JavaScript 的 reduce 方法

203 阅读1分钟

reduce

reduce 方法我们用的很少,但是这个数组的工具函数有用,但是很多人搞不清楚 reduce 具体怎么简单的理解,大道至简嘛!

reduce 其实和 map 很像的,用法也差不多。我们先看 map 方法。

const arr = [1, 2, 3, 4, 5];

const new_arr = arr.map((item, index) => {
    return item + index
})

console.log(new_arr) // [1, 3, 5, 7, 9]

map 的中的函数,接收的参数是: item 和 index。item 就是数组的项目和 index 的数组对应的索引。返回值的是 item 与 index 的和值。

map 大致就是这样,下面说 reduce, reduce 是 map 的扩展板,但是 reduce 接收的参数比 map 多,里面的参数也有相同的部分。reduce 内部函数接收四个参数:

reduce 要有返回值

  • last_reture_value 上次计算返回值,
  • item 遍历的数组项目
  • index 遍历的数组的index
  • arr 数组

不同于 map 的是,reduce 返回的是累计的计算结果,每一次计算结果用作下一次,而map每一次计算后就返回到了一个新的数组中

const arr = [1, 2, 3, 4, 5];

const new_reduce_arr = arr.reduce((last_return_value, item, index, arr) => {
    return last_return_value + item;
}, 99)

console.log(new_reduce_arr) // 114 

reduce api 其实就是一个遍历的 api,本质上功能上有所区别而已