JavaScript Reduce()

274 阅读1分钟

reduce 在工作中一般用来累加,reduce接收两个参数一个参数函数,另一个是初始值initialValue (可选)

callback (执行数组中每个值的函数,包含四个参数)

    1、previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
    2、currentValue (数组中当前被处理的元素)
    3、index (当前元素在数组中的索引)
    4、array (调用 reduce 的数组)

initialValue (作为第一次调用 callback 的第一个参数)。

    type user={
        name:string,
        num:number,
        price:number
    }
    const data = reactive<user[]>([
        {
            name:'张三',
            num:1,
            price:20
        },{
            name:'李四',
            num:2,
            price:30
        },{
            name:'老王',
            num:3,
            price:40
        }
    ])
    const total = data.reduce((prev,next)=>{
       return prev+(next.num*next.price) 
    },0)
//reduce() 的用处——计算数组所有元素的总和

//使用reduce去重
const arr = [1,4,2,5,3,4,5]
const res = []
arr.reduce((pre,next)=>{
    if(!pre.get(next)){
        pre.set(next,1)
        // console.log(pre.set(next,1))
        res.push(next)
    }
    return pre
},new Map())
console.log(res);

Reduce 语法

// Arrow function
reduce((previousValue, currentValue) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ } )
reduce((previousValue, currentValue, currentIndex, array) => { /* ... */ }, initialValue)

// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)

// Inline callback function
reduce(function(previousValue, currentValue) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ })
reduce(function(previousValue, currentValue, currentIndex, array) { /* ... */ }, initialValue)