JS高阶函数reduce()的常用场景

1. reduce()语法

// total	必需。初始值, 或者计算结束后的返回值。
// currentValue	必需。当前元素
// currentIndex	可选。当前元素的索引
// arr	可选。当前元素所属的数组对象。
// initialValue	可选。传递给函数的初始值
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

2. 数组求和

var aa = [1,2,3,4.1,5,'2','9'];
var bb = aa.reduce(function(total,currentValue,currentIndex,arr){
    return total+ Number(currentValue)
},0)
console.log(bb); // 26.1

3. 数组最大值

var aa = [1,2,3,4.1,5,'2','9'];
var bb = aa.reduce(function(total,currentValue,currentIndex,arr){
    return Math.max(Number(total),Number(currentValue))
})
console.log(bb); // 9

4. 数组去重

var aa =[1,2,3,4.1,5,5,'2','2','9',1];
var bb = aa.reduce(function(total,currentValue,currentIndex,arr){
    if(total.indexOf(currentValue) == -1) {
	    total.push(currentValue);
	}
	return total;
},[])
console.log(bb); //  [1, 2, 3, 4.1, 5, "2", "9"]

5. 计算数组中每个元素的出现的次数

var aa = [1,2,3,4.1,5,5,2,2,9,1];
var bb = aa.reduce(function(total,currentValue,currentIndex,arr){
   total[currentValue]?total[currentValue]++:total[currentValue]=1
   return total
},{})
console.log(bb);// {1: 2, 2: 3, 3: 1, 5: 2, 9: 1, 4.1: 1}


站长推荐

1.云服务推荐: 国内主流云服务商,各类云产品的最新活动,优惠券领取。地址:阿里云腾讯云华为云

2.广告联盟: 整理了目前主流的广告联盟平台,如果你有流量,可以作为参考选择适合你的平台点击进入

链接: http://www.fly63.com/article/detial/9530