Array.prototype.reduce((total, curVal, curIdx, arr) => {}, initVal)
reduce()
方法接收一个函数作为累加器,数组中的每个值 (从左到右)开始缩减,最终为一个值,是ES5中新增的又一个数组逐项处理方法
参数:
callback (一个在数组中每一项上调用的函数,接受四个函数:)
total (上一次调用回调函数时的返回值,或者初始值)
curVal (当前正在处理的数组元素)
curIdx (当前正在处理的数组元素下标)
arr (调用 reduce() 方法的数组)
initialValue
(可选的初始值。作为第一次调用回调函数时传给 total 的值)
原方法
1 | var arr = [1, 2, 3, 4] |
手写 __reduce
1 | Array.prototype.__reduce = function (fn, initVal) { |
reduce 的其他用法
去重
1 | const arr = ['a', 'b', 'c', 'a', 'd', 'e', 'r', 'a'] |
数组打平
1 | const arr = [[1,2], 3, [4,5], [6, [7, 8, 9]]] |
数组中重复最多的值
1 | const arr = ['a','b','c','a','d','e','r','a'] |
最大值最小值
1 | const arr = [1, 2, 3, 4, 15, 6, 7, 8, 9] |