网址:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array

Arrary.prototype.reduce()

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

  1. const array1 = [1, 2, 3, 4];
  2. const reducer = (accumulator, currentValue) => accumulator + currentValue;
  3. // 1 + 2 + 3 + 4
  4. console.log(array1.reduce(reducer));
  5. // expected output: 10
  6. // 5 + 1 + 2 + 3 + 4
  7. console.log(array1.reduce(reducer, 5));
  8. // expected output: 15

reducer 接受四个参数

  • 累计值
  • 当前值
  • 当前索引
  • 源数组

语法

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

回调函数第一次执行时,accumulatorcurrentValue 的取值有两种情况:如果调用 reduce() 时提供了 initialValueaccumulator 取值为 initialValuecurrentValue 取数组中的第一个值;如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue 取数组中的第二个值。

Redux 中有一个核心概念是 Reducer,这里的 Reducer 和上面提到的 reducer 相同的概念

  1. const reducer = (state, action){
  2. // ...
  3. return newState
  4. }
  • state 是累计值
  • action 是数组中的当前值
  • return newState 返回新的累积值

详情可以看:reducers(Redux 官网)

「@浪里淘沙的小法师」