语法
函数的语法在API整理中已经收集了:《Array.prototype.reduce() 方法》。这边只介绍下它的应用。
应用
求和
let arr = [1, 2, 3, 4, 5];
let plus = arr.reduce((total, current) => total + current, 0);
console.log(plus); //15
let arr = [{ price: 100, count: 1 }, { price: 200, count: 2 }, { price: 3, count: 3 }];
let plus = arr.reduce(function (total, current) {
return total + current.price * current.count
}, 0);
console.log(plus);//509
数据合并
let keys = ['name', 'age'];
let values = ['jw', 18]; // =>{name:'jw', age:18}
let obj = keys.reduce(function (total, current, index, arr) {
total[current] = values[index];
return total
}, {});
console.log(obj);//{ name: 'jw', age: 18 }
//简化写法
let objSimple = keys.reduce((total, current, index, arr) => (total[current] = values[index], total), {});
console.log(objSimple);//{ name: 'jw', age: 18 }
组合多个函数 compose
reduce() 作为一个高阶函数,用于函数的compose。
//组合多个函数
function sum(a, b) {
return a + b;
}
function toUpper(str) {
return str.toUpperCase();
}
function add(str) {
return '***' + str + '***';
}
console.log(add(toUpper(sum('rui', 'jie'))));//***RUIJIE***
function compose(...fns) {
return fns.reduce(function (total, current, index, arr) {
return function (...args) {
return total(current(...args));
}
})
}
console.log(compose(add, toUpper, sum)('rui', 'jie'));//***RUIJIE***
// 化简
const composeSimple = (...fns) => fns.reduce((total, current) => (...args) => total(current(...args)));
console.log(composeSimple(add, toUpper, sum)('rui', 'jie'));
实现 reduce 源码
Array.prototype.reduce = function (callback, prev) {
for (let i = 0; i < this.length; i++) {
if (typeof prev === 'undefined') {
prev = callback(this[i], this[i + 1], i + 1, this);
i++;
} else {
prev = callback(prev, this[i], i, this);
}
}
return prev;
}