语法

函数的语法在API整理中已经收集了:《Array.prototype.reduce() 方法》。这边只介绍下它的应用。

应用

求和

  1. let arr = [1, 2, 3, 4, 5];
  2. let plus = arr.reduce((total, current) => total + current, 0);
  3. console.log(plus); //15
  1. let arr = [{ price: 100, count: 1 }, { price: 200, count: 2 }, { price: 3, count: 3 }];
  2. let plus = arr.reduce(function (total, current) {
  3. return total + current.price * current.count
  4. }, 0);
  5. console.log(plus);//509

数据合并

  1. let keys = ['name', 'age'];
  2. let values = ['jw', 18]; // =>{name:'jw', age:18}
  3. let obj = keys.reduce(function (total, current, index, arr) {
  4. total[current] = values[index];
  5. return total
  6. }, {});
  7. console.log(obj);//{ name: 'jw', age: 18 }
  8. //简化写法
  9. let objSimple = keys.reduce((total, current, index, arr) => (total[current] = values[index], total), {});
  10. console.log(objSimple);//{ name: 'jw', age: 18 }

组合多个函数 compose

reduce() 作为一个高阶函数,用于函数的compose。

  1. //组合多个函数
  2. function sum(a, b) {
  3. return a + b;
  4. }
  5. function toUpper(str) {
  6. return str.toUpperCase();
  7. }
  8. function add(str) {
  9. return '***' + str + '***';
  10. }
  11. console.log(add(toUpper(sum('rui', 'jie'))));//***RUIJIE***
  12. function compose(...fns) {
  13. return fns.reduce(function (total, current, index, arr) {
  14. return function (...args) {
  15. return total(current(...args));
  16. }
  17. })
  18. }
  19. console.log(compose(add, toUpper, sum)('rui', 'jie'));//***RUIJIE***
  20. // 化简
  21. const composeSimple = (...fns) => fns.reduce((total, current) => (...args) => total(current(...args)));
  22. console.log(composeSimple(add, toUpper, sum)('rui', 'jie'));

实现 reduce 源码

  1. Array.prototype.reduce = function (callback, prev) {
  2. for (let i = 0; i < this.length; i++) {
  3. if (typeof prev === 'undefined') {
  4. prev = callback(this[i], this[i + 1], i + 1, this);
  5. i++;
  6. } else {
  7. prev = callback(prev, this[i], i, this);
  8. }
  9. }
  10. return prev;
  11. }