js中数组的递归方法reuduce()

64 篇文章 3 订阅
17 篇文章 0 订阅

一、数组原型的递归方法Array.prototype.reduce()

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

reduce()函数接收4个参数:
  1. Accumulator (acc) (累计器)
  2. Current Value (cur) (当前值)
  3. Current Index (idx) (当前索引)
  4. Source Array (src) (源数组)
reduce()语法

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

简写看就是arr.reduce(callback,[initialValue])

reduce()参数
  • callback
    执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数:
  • accumulator 累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(见于下方)。

  • currentValue数组中正在处理的元素。

  • index 可选 数组中正在处理的当前元素的索引。 如果提供了initialValue,则起始索引号为0,否则从索引1起始。

  • array可选 调用reduce()的数组

  • initialValue可选
    作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。

  • 返回值
    函数累计处理的结果

官方给出了累加的示例
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
这是一些示例方法
export default {
    mixins: [],
    inject: [],
    components: {
    },
    data () {
      return {
        arr: [1, 2, 3, 4, 5],
        b: [1, 3, 4, 6, 7, 1, 3, 5, 3, 2, 4, 1, 2, 4, 5]
      }
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        const a = this.arr
        console.warn(a.reduce((a, b) => a + b)); // 递归求和15

        console.warn(a.reduce((a, b) => a > b ? a : b)); // 递归求最大值5

        console.warn(a.reduce((a, b) => a < b ? a : b)); // 递归求最小值1


        const b = this.b.reduce((a, b) => {
            if(!a.includes(b)) {
                return a.concat(b)
            }else{
                return a
            }
        }, [])
        console.warn(b); // 数组去重[1, 3, 4, 6, 7, 5, 2]

		const c = this.b.reduce((a, b) => {
              if(b in a) {
                  a[b]++
              }else{
                  a[b] = 1
              }
              return a
          }, {})
        console.log('次数', c) // {1: 3, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1, 7: 1}

      },
      test() {

      }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值