个人技术分享

语法:集合.reduce((前一次回调函数的返回值,当前项) => 方法体,前一次回调函数的返回值参数的初始值 )

作用:reduce()函数主要用于对数组进行迭代和转换。

//对数组进行求和:
corst rumbers = [1,2,3,4,5];
const sum = numbers.reduce(function(total,currentvalue){
    return total + currentvalue;
}) ;
conso1e.log(sum) ; //输出15


//箭头函数的数组进行求和:
const sum2 = numbers.reduce((total,currentvalue) => total + currentvalue, 0)


//对数组进行计数:
const fruits = ['app1e', 'banana', ' orange', 'app1e', 'watermelon'];
const count = fruits.reduce(function(tota1,currentvalue) {
if (currentvalue in tota1){
tota1[currentvalue]++;
} else {
tota1[currentvalue] = 1;
l
return tota1 ;
},{});
console.1og(count) ; //输出 {app1e: 2, banana: 1, orange: 1,watermelon: 1}

//对数组进行过滤:
const numbers = [1,2,3,4,5];
const filtered = numbers.reduce(function(total,currentvalue){
if (currentvalue % 2=== 0) tota1.push(currentvalue) ;
return total ;
},[]);
conso1e.1og(filtered); //输出 [2,4]