ES6 reduce方法

reduce()是数组的归并方法 可同时将前面数组遍历产生的结果与当前项进行运算

reduce第一个参数是一个函数 函数里面有四个参数分别是 累加器 当前值 当前索引 源数组

const arr = [4, 2, 1, 4];
let res = arr.reduce((temp, item, index, data) => {
            console.log(temp, item);
            return temp + item;
        })
 console.log(res);
//4 2
//6 1
//7 4
//11

 

如果reduce没有第二个参数就把数组中第一项给累计器   从第二项开始遍历

如果reduce有第二个参数   把第二个参数给累计器   从数组第一项开始遍历

 

const arr = [4, 2, 1, 4];
let res = arr.reduce((temp, item, index, data) => {
            console.log(temp, item);
            return temp + item;
        },10)
        console.log(res);
//10 4
//14 2
//16 1
//17 4
//21

 


版权声明:本文为m0_45887053原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。