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>
运行结果: