Handwritten array reduce function

(1) Reduce syntax

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

reduce receives two parameters

example:

let arr = [1, 2, 3, 4, 5]
// 下标是奇数的元素和
var result = arr.reduce((total, item, index) => {
  total += (index % 2 ? item : 0)
  return total
}, 0)

console.log(result) // 6

Initial value is 0

(2) Write reduce by hand below

Array.prototype.reduce = function (callback, initValue) {
  let result = initValue // result 赋值 为传过来的初始值
  for (var index = 0; index < this.length; index++) {
    result = callback(result, this[index], index, this) // 循环重新计算 result
  }
  return result // 返回result
}

transfer:

Array.prototype.reduce = function (callback, initValue) {
  let result = initValue
  for (var index = 0; index < this.length; index++) {
    result = callback(result, this[index], index, this)
  }
  return result
}

// 下标是奇数的元素和
let arr = [1, 2, 3, 4, 5]
var res = arr.reduce((total, item, index) => {
  total += (index % 2 ? item : 0)
  return total
}, 0)

console.log(res) // 6

 

Guess you like

Origin blog.csdn.net/Luckyzhoufangbing/article/details/108906244