JavaScript中reduce的基本用法
前言
本篇为文章主要总结了reduce()的用法,可能有一些难理解,可以多看几遍,然后动手实际操作。
一、首先了解一下什么是reduce
1、reduce() 方法接收一个函数作为累加器,reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素。
(实际上就是封装好的一个循环)
(看不懂,往下看简单的实例)
语法:arr.reduce(callback,[initialValue])
callback:函数中包含四个参数
- previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
- currentValue (数组中当前被处理的元素)
- index (当前元素在数组中的索引)
- array (输入数组)
initialValue (作为第一次调用 callback 的第一个参数。)
2、实例
(1)
const 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}
补充
当然,你也可以使用它来完成一些数组的去重,对象的合并,数字的累加等等功能。
总结
最后感谢大家的阅读!