reduce妙用

##语法数组

/*
* @param accumulator 函数传进来的初始值或上一次回调的返回值
* @param currentValue 数组中当前处理的元素值
* @param currentIndex 当前元素索引
* @param arr  当前元素所属的数组自己
* @param initialValue 初始值,能够是数组或者对象,有妙用
*/
    array.reduce(function(accumulator, currentValue, currentIndex, arr), initialValue)
  • 注意初始值的传递与不传递的区别:回调函数第一次执行时,accumulator 和currentValue的取值有两种状况:若是调用reduce()时提供了initialValue,accumulator取值为initialValue,currentValue取数组中的第一个值;若是没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值

例子:

  • 累加
let ary = [1,2,3,4];
let sum =  ary.reduce((a,b) => {
    return a + b;
}) // 10
  • 初始值传对象,统计数组中相同项的个数
let car  = ['BMW', 'Benz', 'Tesla', 'BMW', 'Toyota'];
let obj = car.reduce((a, b) => {
    a[b] = a[b] ? a[b] + 1 : 1;
    return a
},{}) 
// obj结果为 {
    BMW: 2,
    Benz: 1,
    Tesla: 1,
    Toyota: 1
}
  • 同时代替map和filter,传入数组,好比要过滤数组中的值乘以2后大于100的项
let ary = [20,30,60,55,10];
let result = ary.reduce((a,b) => {
    if(b * 2 > 100) {
        a.push(b * 2)
    }
    return a;
}, []);
// 结果为[120,110]
  • tip foreach没有返回值,为undefined
相关文章
相关标签/搜索