1. 程式人生 > >ES6 reduce的實現

ES6 reduce的實現

reduce 方法對累計器和陣列中的每個元素(從左到右)應用一個函式,將其簡化為單個值。
reducer 函式接收4個引數:

    1. Accumulator (acc) (累計器)
    1. Current Value (cur) (當前值)
    1. Current Index (idx) (當前索引)
    1. Source Array (src) (源陣列)
有預設引數
const arr = [1, 2, 3]
let result = arr.reduce(function(val, item, index, origin) {
  return val + item
}, 0)
無預設引數
result = arr.reduce(function(val, item, index, origin) {
  return val + item
})
求平均值
result = arr.reduce(function(val, item, index, origin) {
  const res = val + item
  if (index === origin.length-1) {
    return res/origin.length
  } else {
    return res
  }
})
console.log(result)
實現reduce
Array.prototype.myRedece = function(reducer, initValue){
  for (let i = 0; i < this.length; i++) {
    initValue = reducer(initValue, this[i], i, this)
  }
  return initValue
}

const res = arr.myRedece(function(val, item){
  return val + item
}, 0)

console.log(res)
實現reduceRight
Array.prototype.myRedeceRight = function(reducer, initValue){
  for (let i = this.length -1 ; i >= 0; i--) {
    initValue = reducer(initValue, this[i], i, this)
  }
  return initValue
}

const res1 = arr.myRedece(function(val, item){
  return val + item
}, 0)

console.log(res1)