Skip to content

JS 之 reduce 的模拟实现 #46

Open
@myLightLin

Description

@myLightLin

reduce 的语法

基本使用如下:

arr.reduce(callbackFn, initialValue)

其中 callbackFn 接收四个参数,分别是执行结果,当前迭代项,当前索引以及原数组。

reduce 的模拟实现

const orignalReduce = Array.prorotype.reduce
Array.prototype.reduce = orignalReduce || function(cb, initValue) {
  const array = this
  const startIndex = initValue !== undefined ? 0 : 1
  let pre = initValue ?? array[0]
  for (let i = startIndex; i < array.length; i++) {
    const curr = array[i]
    pre = cb(pre, curr, i, array)
  }
  return pre
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions