想要模拟reduce,就要先明白reduce的作用,reduce是数组的一个方法,可以对数组进行累加效果,比如,求数组每一项相加的和:
const arr = [1 ,2, 3, 4]const resuslt = arr.reduce((acc, cur, idx) => {return acc + cur})
参数:
- 第一项:reducer是个函数,主要处理逻辑写在这里边,接受4个参数
- acc,累加结果
- cur,当前数据项
- idx,当前索引值
- source,源数组
- 第二项:initValue,可选,有值的时候传给acc
看一下acc取值情况:第一次执行reducer的时候,如果initValue有值,就传给acc,如果没有值,acc取数组第一项,cur取数组第二项
模拟实现:
Array.prototype.myReduce = function (reducer, initValue) {let acc = initValuelet index = 0if (!initValue) {acc = this[index]index = 1}for (; index < this.length; index++) {acc = reducer(acc, this[index], index, this)}return acc}
同理实现reduceRight
Array.prototype.myReduceRight = function (reducer, initValue) {let acc = initValuelet index = this.length - 1if (!initValue) {acc = this[index]index = index - 1}for (; index >= 0; index--) {acc = reducer(acc, this[index], index, this)}return acc}
