手書き配列リデュース機能

(1)構文を減らす

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

reduceは2つのパラメーターを受け取ります

例:

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

初期値は0です

(2)以下に手書きでreduceを書く

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
}

転送:

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

 

おすすめ

転載: blog.csdn.net/Luckyzhoufangbing/article/details/108906244