定义
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)(array是数组实例)
参数作用如下
这里我们先从reduce的第二个参数initialValue开始讲解
参数解析
initialValue
initialValue是一个非必需参数,她接受一个初始值传给total,作为total的初始值
function(total, currentValue, currentIndex, arr)
function是一个必需参数,用于执行每个数组元素的函数
function内部的参数及含义
- total
- 必需参数
- 接收
initialValue作为函数迭代的初始值 - 如果
initialValue没有初始值,total则以数组的第一个元素作为初始值 - 接收每一轮计算结束之后的返回值
- currentValue
- 必需参数
- 当
initialValue存在时,以数组的一个元素作为当前的值 - 当
initialValue不存在时,以数组的第二个元素作为当前的值 - 当一轮计算结束之后指向下一个值
- currentIndex
- 非必需参数
currentValue元素对应的数组下标
- currentIndex
- 非必需参数
- 指代当前数组
total与currentValue在运行过程中的展示
//有初始值的情况
let arr = [1, 3, 4, 6, 3, 0];
arr.reduce((total, currentValue) => {
console.log('total: ' + total + '; currentValue: ' + currentValue)
return total + currentValue;
}, 0);
运行结果
//无初始值的情况
let arr = [1, 3, 4, 6, 3, 0];
arr.reduce((total, currentValue) => {
console.log('total: ' + total + '; currentValue: ' + currentValue)
return total + currentValue;
});
运行结果
简单用法
1.数组求和
let arr = [1, 3, 4, 6, 3, 0];
let result = arr.reduce((total, currentValue) => {
return total + currentValue;
});
// result = 17
还有许多类似的用法,比如说连减,连乘,连除
// 减法的运用
let arr = [1, 3, 4, 6, 3, 0];
let result = arr.reduce((total, currentValue) => {
return total - currentValue;
}, 20);
//result = 3
2.阶乘
// fill() es6提出的新方法,用于填充一个数组
let arr = new Array(5).fill();
// 此处currentValue虽然没有使用,但不能省略
let result = arr.reduce((total, currentValue,currentIndex) => {
return total * (currentIndex + 1);
},1);
// result = 120
3.数组的最大(小)值
let arr = [1, 3, 4, 6, 3, 0];
let result = arr.reduce((total, currentValue) => {
return Math.max(total, currentValue)
});
高级用法
1.数组去重
let arr = [1, 3, 4, 6, 3, 0];
let result = arr.reduce((total, currentValue) => {
//total.indexOf(currentValue) === -1 ? total.push(currentValue) : '' 两种写法效果相同
total.indexOf(currentValue) === -1 && total.push(currentValue)
return total
},[]);
2.计算数组中每个元素出现的次数
let names = ['A', 'B', 'C', 'D', 'A','E','D'];
var nameNum = names.reduce((total,currentValue)=>{
if(currentValue in total){
total[currentValue]++
}else{
total[currentValue] = 1
}
return total
},{})
console.log(nameNum); //{A: 2, B: 1, C: 1, D: 2, E: 1}
3.数组扁平化
let arr = [[0, 1], [2, 3], [4, 5]]
let newArr = arr.reduce((total,currentValue)=>{
return [...total,...currentValue]
},[])
console.log(newArr); // [0, 1, 2, 3, 4, 5]
4.对象属性求和
var result = [
{
subject: 'math',
score: 10
},
{
subject: 'english',
score: 30
}
];
var sum = result.reduce(function(total, currentValue) {
return currentValue.score + total;
}, 0);
console.log(sum) //40
总得来说,reduce的核心就是对total的理解
接收每一轮计算结束之后的返回值
另外还有一个方法叫reduceRight(),用法和reduce相同,只是遍历的顺序相反,他从数组的最后一项开始遍历,向前遍历到第一项