Detailed explanation of reduce function in ES6

Syntax format of reduce function

arr.reduce(callback,[initialValue])
/* callback (执行数组中每个值的函数,包含四个参数)

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

        initialValue (作为第一次调用 callback 的第一个参数(初始previousValue)。)*/

The code below is better to understand

//数组求和
var arr = [1, 2, 3, 4];

 var sum = arr.reduce(function(prev, cur, index, arr) {
    
    
 //调试,实在不明白可以单步调试一下
// debugger
     console.log(prev, cur, index,arr);
     return prev + cur;
     //下面的指定pre的初始值为0
 },0)
 console.log(arr, sum);

The essence of this function is to traverse the array, cur and index will move from the beginning of the array to the end, the return value of the function is used as the pre value of the next call to the function (if the traversal is completed, it will be the return value of reduce)
. The first call to the function: pre = 0 ,cur = 1, index = 0, arr=[1,2,3,4] returns (the next pre) 1; the
second call to the function: pre = 1,cur = 2, index = 1, arr=[ 1,2,3,4] returns (the next pre) 3; the
third call to the function: pre = 3, cur = 3, index = 2, arr=[1,2,3,4] returns (the next Pre) 6; the
fourth call to the function: pre = 6, cur = 4, index = 3, arr=[1,2,3,4] returns the return value of the reduce function 10;

Look at the following demon (advanced use of reduce) to deepen your understanding


//reduce函数的高级用法,求数组中元素的出现次数

let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
let nameNum = names.reduce((pre,cur,index)=>{
    
    
    console.log(pre,cur,index)
    if(cur in pre){
    
    
        pre[cur]++
    }else{
    
    
        pre[cur] = 1
    }
    console.log(pre,cur,index)
    return pre
},
    //这里设置pre初始值是空对象
    {
    
    })
console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}
//数组的去重
    let arr = [1,2,3,4,5,1,3,7,2,1,3,4,8,5,5,7]
    newarr = arr.reduce((pre,curr,index,arr)=>{
    
    
       // debugger
        console.log(pre,curr)
        //console.log(typeof pre,typeof curr)
        //不可以写成curr in pre  原因往下看
        if (pre.includes(curr)) console.log(curr+"已经包含在对象中了");
        else pre.push(curr)
        return pre
    },[])
    console.log(arr)
    console.log(newarr)*/

In the above two examples, the first one can use the in keyword to determine whether an attribute is in the object.
But there is a pit, why the following judge whether the element is in the array can not use in? This involves the difference between in and includes, please see the following blog

The difference between ES6 in and includes
If there is any error in the article, you are welcome to criticize and correct it.

Guess you like

Origin blog.csdn.net/qq_44606064/article/details/109545242