reduce()方法

数组的reduce()方法接受一个函数作为累加器,将数组的每个值从左到右开始用该函数进行处理,最终输出为一个值

最常见的用法就是数组求和:

let arr = [5, 4, 3, 2, 1];
let reducer = (total, currentValue, currentIndex, arr) => {
  console.log('total', total);
  console.log('currentValue', currentValue);
  console.log('currentIndex', currentIndex);
  console.log('arr', arr);
  return total + currentValue
}
console.log(arr.reduce(reducer, 100))
console.log(arr.reduce(reducer))
console.log(arr)

语法:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

其中参数:
- total:初始值或者计算后的返回值,必须
- currentValue:当前元素,必须
- currentIndex:当前元素索引,可选
- arr:当前数组,可选
- initialValue:传递给函数的舒初始值,可选

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

参考

猜你喜欢

转载自blog.csdn.net/duola8789/article/details/80081181