- 数组求和?
- 求数组的最大值?
- 数组元素去重?
- 统计字符串中每个字符出现的次数?
- 二维数组转化为一维数组?
一个reduce()函数就可以统统帮你搞定!
一. 前言
reduce函数()是数组对象中的一个内置函数.reduce() 函数接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值.
二. 语法
Array.prototype.reduce(callback(previousValue, currentValue, index, array), [initialValue]);
参数 | 描述 |
---|---|
callback | previousValue: 上一次计算后返回的值. currentValue: 当前遍历的元素的值. index: 当前遍历元素所在的下标. array: 源数组. |
initialValue(可选) | 初始值,如果我们不设定它,它的默认值为数组的第一个元素. |
三. 实战
1. 数组求和
let numbers = [1, 2, 3];
let sum = numbers.reduce(function (accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log('sum is ' + sum); // sum is 6
解析: accumulator在初始值为0的基础上,不断累加数组里面的元素,执行过程如下表:
函数调用 | accumulator | currentValue | 函数返回的结果 |
---|---|---|---|
第一次调用 | 0 | 1 | 1 |
第二次调用 | 1 | 2 | 3 |
第三次调用 | 3 | 3 | 6 |
2. 求数组的最大值
let numbers = [1, 2, 3];
let max = numbers.reduce((maxValue, currentValue) => {
return maxValue > currentValue ? maxValue: currentValue;
});
console.log('max is', max); // max is 3
// 当然了,对于求数组的最大值,我更推荐你用下面这种方法
max = Math.max(...numbers);
console.log('max is', max); // max is 3
解析: 这里没有指定初始值initialValue,那么initialValue的值默认就是数组的第一个元素1,所以这里maxValue第一次传入的值就是1.整个函数只被调用2次.执行过程如下表:
函数调用 | maxValue | currentValue | 函数返回的结果(求最大值,谁大要谁) |
---|---|---|---|
第一次调用 | 1 | 2 | 2 |
第二次调用 | 2 | 3 | 3 |
3. 数组元素去重
let numbers = [1, 2, 3, 3];
let sets = numbers.reduce(function (setArray, currentValue) {
// 如果这个元素不存在sets数组中,就放进去
if (setArray.indexOf(currentValue) === -1) {
setArray.push(currentValue);
}
return setArray;
}, []);
console.log('sets is', sets); // sets is [ 1, 2, 3 ]
// (更优雅的写法) 我知道,优秀的你可能会这么做.好了,我夸过你了,你是不是得回我一个赞?
console.log('sets is', [...new Set(numbers)]);
解析: 初始值为空数组,如果源数组的元素刚好在setArray数组里面不存在,就将这个元素放入setArray数组中.
4. 统计字符串中每个字符出现的次数
let str = 'abcab';
let charRepeatTimes = [...str].reduce((repeatTimes, currentValue) => {
repeatTimes[currentValue] ? repeatTimes[currentValue]++ : repeatTimes[currentValue] = 1;
return repeatTimes;
}, {});
console.log('charRepeatTimes is', charRepeatTimes);
// charRepeatTimes is { a: 2, b: 2, c: 1 }
解析: 初始值initialValue为一个空对象,通过这个对象的key来保存单个字符,value来保存单个字符出现的次数,这样就能统计每个字符出现的次数了.
5. 二维数组转化为一维数组
let twoDimensionalArray = [
[1, 3, 5],
[2, 4, 6]
];
let oneDimensionalArray = twoDimensionalArray.reduce((array, currentValue) => {
array.push(...currentValue);
return array;
}, []);
console.log('oneDimensionalArray is', oneDimensionalArray);
// oneDimensionalArray is [ 1, 3, 5, 2, 4, 6 ]
解析: 初始值initialValue为一个空数组,使用这个数组来保存二维数组中出现的每个元素.