JavaScript中reduce的基本用法

JavaScript中reduce的基本用法

前言

本篇为文章主要总结了reduce()的用法,可能有一些难理解,可以多看几遍,然后动手实际操作。

一、首先了解一下什么是reduce

1、reduce() 方法接收一个函数作为累加器,reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素。
(实际上就是封装好的一个循环)
(看不懂,往下看简单的实例)

语法:arr.reduce(callback,[initialValue])
callback:函数中包含四个参数
- previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
- currentValue (数组中当前被处理的元素)
- index (当前元素在数组中的索引)
- array (输入数组)
initialValue (作为第一次调用 callback 的第一个参数。)

2、实例

1const arr = [1, 2, 3, 4, 5]
const sum = arr.reduce((prev, cur) => {
    return prev + cur
}, 1)
console.log(sum) // 16

等价于
const arr = [1, 2, 3, 4, 5]
let initValue = 1;
for(int i=0; i< arr.length; i++){
	initValue += arr[i];
}
console.log(sum) // 16

这里1为累加器的初始参数值。

当然该函数也可以用户数组,对象的循环当中

const people = [
    {
        name: 'huahua',
        height: 150
    },
    {
        name: 'lala',
        height: 160
    },
    {
        name: 'bengbeng',
        height: 18
    }
];

const result = people.reduce((prev, cur) => {
	prev.name += cur.name+"|";
	prev.height += cur.height;
    return prev
}, {name:'',height:0})
console.log(result) //{name: 'huahua|lala|bengbeng|', height: 328}

等价于
var initValue = {name:'', height:0};
for(int i=0; i< people.length; i++){
	initValue.name += people[i].name+"|";
	initValue.height += people[i].height;
}
console.log(result) //{name: 'huahua|lala|bengbeng|', height: 328}

实际内部实现 使用递归 处理每一次的返回变量 所以我们可以灵活的使用它做很多事情
var initValue = {name:'', height:0};
callBack=(prev, cur, index, arr)=>{
	prev.name += cur.name+"|";
	prev.height += cur.height;
	if(index != arr.length - 1){
		++index;
		callBack(prev, arr[index], index, arr);
	}
	return prev;
}
const result = callBack(initValue, people[0], 0, people);
console.log(result) //{name: 'huahua|lala|bengbeng|', height: 328}

补充

当然,你也可以使用它来完成一些数组的去重,对象的合并,数字的累加等等功能。

总结

最后感谢大家的阅读!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值