reduce 函数详解

reduce 方法介绍:

reduce() 方法对数组每个元素执行一个 reduce 函数,将其结果汇总为单个返回值。

1
const array = [1, 2, 3, 4];
2
const reducer = (accumulator, currentValue) => accumulator + currentValue;
3
// 1 + 2 + 3 + 4
4
console.log(array.reduce(reducer));  // 10

reduce 方法使用场景:

1. 对数组进行求和
1
参见上段代码
2. 将二维数组转换为一维数组
1
let array = [[1, 2], [3, 4], [5, 6]];
2
const reducer = (acc, cur) => acc.concat(cur);
3
let result = array.reduce(reducer, [])   // 将 [] 作为回到函数第一个参数
4
console.log(result); //[1, 2, 3, 4, 5, 6]
3. 计算数组每个元素出现的次数
1
let names = ['jser', 'jser', 'javaer', 'javaer', 'phper', 'pythener']
2
let obj = {};
3
names.reduce((acc, cur) => {
4
    acc[cur]? acc[cur]++ : acc[cur] = 1;
5
    return acc;
6
}, obj)   // 将 obj 作为回到函数第一个参数 obj
7
8
//解析:
9
//第一次遍历:acc = {} cur = "jser"
10
//第二次遍历:acc = {jser: 1} cur = "jser"
11
//第三次遍历:acc = {jser: 2} cur = "javaer"
12
//第四次遍历:acc = {jser: 2, javaer: 1} cur = "javaer"
13
//第五次遍历:acc = {jser: 2, javaer: 2} cur = "phper"
14
//第六次遍历:acc = {jser: 2, javaer: 2, phper: 1} cur = "pythener"
15
//第七次退出:acc = {jser: 2, javaer: 2, phper: 1, pythen: 1}  
16
console.log(obj) // {jser: 2, javaer: 2, phper: 1, pythen: 1}

filter 方法介绍:

filter() 方法创建一个新数组,其成员是通过提供函数测试的所有元素。

1
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
2
const result = words.filter(word => word.length > 6);  // 元素的长度大于6的通过测试
3
console.log(result); ["exuberant", "destruction", "present"]