es6之reduce用法

1 reduce源码

/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;

2 参数说明

2.1 第一个参数: callback函数

执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数:

  • previousValue累计器
  • currentValue 当前值(当前对象)
  • currentIndex 当前索引(一般未空)
  • array 数组(一般为空)

previousValue参数

累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(见于下方)。

currentValue参数

数组中正在处理的元素。

index 可选

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

array可选

调用reduce()的原数组

2.2 第二个参数: initialValue可选

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

3 使用示例

<template>

  <div>
    <ol>
      <li v-for="e in books" :key="e">{{e.name}}-{{e.author}}-{{e.price}}</li>
    </ol>
    <span>{{sumPrice1}}</span>
  </div>

  <div>
    <span>{{sumPrice2}}</span>
  </div>

</template>

<script>

export default {
  name: "App",
  data() {
    return {
      books: [
        {name: "笑傲江湖1", author: "admin", price: 88},
        {name: "笑傲江湖2", author: "admin", price: 88},
        {name: "笑傲江湖3", author: "admin", price: 88},
        {name: "笑傲江湖5", author: "admin", price: 88},
      ]
    }
  },
  computed: {
    // 全部参数
    sumPrice1:{
      get(){
        return this.books.reduce(function (accumulator, currentValue,currentIndex, array){
          console.log("当前索引",currentIndex)
          console.log("数组",array)
          return accumulator + currentValue.price
        },0);
      }
    },
    // 简写参数
    sumPrice2:{
      get(){
        return this.books.reduce((accumulator, currentValue)=>accumulator + currentValue.price,0);
      }
    }
  }
}
</script>

<style scoped>

</style>

运行结果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

L-960

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值