网址:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array
Arrary.prototype.reduce()
reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
const array1 = [1, 2, 3, 4];const reducer = (accumulator, currentValue) => accumulator + currentValue;// 1 + 2 + 3 + 4console.log(array1.reduce(reducer));// expected output: 10// 5 + 1 + 2 + 3 + 4console.log(array1.reduce(reducer, 5));// expected output: 15
reducer 接受四个参数
- 累计值
- 当前值
- 当前索引
- 源数组
语法
array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
回调函数第一次执行时,accumulator 和 currentValue 的取值有两种情况:如果调用 reduce() 时提供了 initialValue,accumulator 取值为 initialValue,currentValue 取数组中的第一个值;如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue 取数组中的第二个值。
Redux 中有一个核心概念是 Reducer,这里的 Reducer 和上面提到的 reducer 相同的概念
const reducer = (state, action){// ...return newState}
state是累计值action是数组中的当前值return newState返回新的累积值
详情可以看:reducers(Redux 官网)
「@浪里淘沙的小法师」
