JS 数组方法map、filter、reduce方法实现

262 阅读1分钟

JS 数组方法map、filter、reduce方法实现

1.map

Array.prototype._map = function(fn) {
  if (this.length < 1) return
  let newArr = []
  for (let i = 0; i < this.length; i++) {
    newArr.push(fn(this[i], i, this))
  }
  return newArr
}

2.filter

Array.prototype._filter = function(fn) {
  if (this.length < 1) return
  let newArr = []
  for (let i = 0; i < this.length; i++) {
    if (fn(this[i], i, this)) {
      newArr.push(this[i])
    }
  }
  return newArr
}

3.reduce

Array.prototype._reduce = function (fn, initValue) {
  if (initValue === undefined && !this.length) {
    throw new Error("myReduce of empty array with no initial value")
  }
  let result = initValue ? initValue : this[0]
  for (let i = initValue ? 0 : 1; i < this.length; i++) {
    result = fn(result, this[i], i, this)
  }
  return result
}