js Array.prototype.reduce使用

首先先认识一下他的使用方法

arr.reduce(callback[, initialValue]) 第一个参数是回调函数 第二参数是初始值 有一点需要的注意的是这个初始值的类型就是这个数组reduce后返回值的类型,下面我们用几个例子来看一下

var total = [0, 1, 2, 3].reduce(function(sum, value) {
    return sum + value;
}, 0); // total is 6

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
    return a.concat(b);
}, []);  //打印flattened输出  [0, 1, 2, 3, 4, 5]

总结:先说第二参数initialValue, 初始值的类型就是整个reduce返回值的类型,第一个例子初始值是0 是Number类型 那么接受值的total也是Number类型, 同理第二例子初始值类型是数组,返回的flattened也应该是数组类型;接下下来说一下这个callback回调函数, 现在只针对上面的来个例子来说,大家使用的时候注意一下,上面两个回调函数的第一个参数我们可以把它理解为就是初始化的值,回调函数的第二个值就是对应数组中的元素,eg:第一个例子中value就是数组【0, 1, 2, 3】中的元素,理解这一点就知道第一个例子就是求和, 第二例子中b是[[0, 1], [2, 3], [4, 5]]这个二维数组中的一个对象, 理解了这个就会明白这个其实是把[[0, 1], [2, 3], [4, 5]]这个数组拼接到一个数组中。

接下来在给大家看几个例子就会明白

1.第一个例子使用箭头函数 不熟悉的同学可以去查看阮一峰的ES6 讲的很详细 感兴趣的同学可以去看看


[0, 1, 2, 3, 4].reduce(
  (accumulator, currentValue, currentIndex, array) => {
    return accumulator + currentValue;
  },
  10
);
callback accumulator currentValue currentIndex array return value first call 10 0 0 [0, 1, 2, 3, 4] 10 second call 10 1 1 [0, 1, 2, 3, 4] 11 third call 11 2 2 [0, 1, 2, 3, 4] 13 fourth call 13 3 3 [0, 1, 2, 3, 4] 16 fifth call 16 4 4 [0, 1, 2, 3, 4] 20

2.第二个例子是统计数组中相同元素出现的次数 需要注意的是初始值是个空对象 所以用于接受countedNames也应该是个对象

var names = [Alice, Bob, Tiff, Bruce, Alice];

var countedNames = names.reduce(function (allNames, name) {
          
    
  if (name in allNames) {
          
   
    allNames[name]++;
  }
  else {
          
   
    allNames[name] = 1;
  }
  return allNames;
}, {
          
   });
// countedNames is:
// { Alice: 2, Bob: 1, Tiff: 1, Bruce: 1 }

3.第三个例子就是罗列出各自喜欢的图书 ...是ES6中的遍历

var friends = [{
          
   
  name: Anna,
  books: [Bible, Harry Potter],
  age: 21
}, {
          
   
  name: Bob,
  books: [War and peace, Romeo and Juliet],
  age: 26
}, {
          
   
  name: Alice,
  books: [The Lord of the Rings, The Shining],
  age: 18
}];

// allbooks - list which will contain all friends books +  
// additional list contained in initialValue
var allbooks = friends.reduce(function(prev, curr) {
          
   
  return [...prev, ...curr.books];
}, [Alphabet]);

// allbooks = [
//   Alphabet, Bible, Harry Potter, War and peace, 
//   Romeo and Juliet, The Lord of the Rings,
//   The Shining
// ]
参考API :
经验分享 程序员 微信小程序 职场和发展