乐趣区

关于javascript:js高手必知api-使用数组方法reduce简化代码

reduce 定义

遍历数组中的每项,并由函数解决后,将其后果汇总为单个返回值

语法

arr.reduce(function(total, current,currentIndex, arr), initialValue)

typescript 办法定义

    reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
    reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
    reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;

案例

过滤出满足条件的,存入数组中

const arr=[
    {value:10},{value:11},{value:12}
]

const arr2 = arr.reduce((temp,item) => {if(item.value>10){temp.push(item.value);
    }
    return temp
},[])

数组求和

let arr=[
    {value:10},{value:11},{value:12}
]

let mean=arr.reduce((temp,item,index)=>{return temp+item;})

应用 reduce 求平均数,一步到位

let mean=arr.reduce((temp,item,index)=>{if(index < arr.length-1){return temp+item;}else{return (temp+item)/arr.length;
    }
})

参考资料:

  • https://developer.mozilla.org…
  • https://www.runoob.com/jsref/…
退出移动版