arr.reduce()用法

1. 语法:reduce(function(total,currentValue, index,arr){},{})

  reduce接收两个参数,第一个参数是函数,第二个参数是第一个参数中total的初始值
  (1) 第一个参数 function 中

    total就是初始值或者每次计算结束的返回值(必填)

    currentValue就是字面意思,每次循环运算当前值(必填)

    index每次下标(选填)

    arr指的是现在循环的数组(选填)
  (2) 第二个参数是第一个参数中total的初始值

2. 用法

  (1) 数组求和

let arr = [1,2,3,4,5]

let total = arr.reduce((total, item) => {
   return total += item
}, 0)

console.log(total) // 15

  (2) 数组去重

let arr = [1,2,3,3,3,3,4,4,4,5]

let newArr = arr.reduce((all, item) => {
   if (!all.includes(item)){
      all.push(item)
   }
   return all
}, [])

console.log(newArr) // (5) [1, 2, 3, 4, 5]

  (3) 统计数组或者字符串中出现的次数

let arr = [1,2,3,3,3,3,4,4,4,5]

let obj = arr.reduce((add, item) => {
  if (add[item]) {
    add[item] ++
  } else {
    add[item] = 1
  }
  return add
}, {})
console.log(obj)
// {1: 1, 2: 1, 3: 4, 4: 3, 5: 1}

 

posted @ 2022-11-20 00:38  cros  阅读(1143)  评论(0)    收藏  举报