想要模拟reduce,就要先明白reduce的作用,reduce是数组的一个方法,可以对数组进行累加效果,比如,求数组每一项相加的和:

    1. const arr = [1 ,2, 3, 4]
    2. const resuslt = arr.reduce((acc, cur, idx) => {
    3. return acc + cur
    4. })

    参数:

    • 第一项:reducer是个函数,主要处理逻辑写在这里边,接受4个参数
      • acc,累加结果
      • cur,当前数据项
      • idx,当前索引值
      • source,源数组
    • 第二项:initValue,可选,有值的时候传给acc

    看一下acc取值情况:第一次执行reducer的时候,如果initValue有值,就传给acc,如果没有值,acc取数组第一项,cur取数组第二项

    模拟实现:

    1. Array.prototype.myReduce = function (reducer, initValue) {
    2. let acc = initValue
    3. let index = 0
    4. if (!initValue) {
    5. acc = this[index]
    6. index = 1
    7. }
    8. for (; index < this.length; index++) {
    9. acc = reducer(acc, this[index], index, this)
    10. }
    11. return acc
    12. }

    同理实现reduceRight

    1. Array.prototype.myReduceRight = function (reducer, initValue) {
    2. let acc = initValue
    3. let index = this.length - 1
    4. if (!initValue) {
    5. acc = this[index]
    6. index = index - 1
    7. }
    8. for (; index >= 0; index--) {
    9. acc = reducer(acc, this[index], index, this)
    10. }
    11. return acc
    12. }