Reduce

陣列累加器,從左到右依序開始縮減,最終回傳一個總值。

arr.reduce(
  callback[(accumulator, currentValue, currentIndex, array)],
  initialValue
);

callback - 處理陣列每個元素的函式,可傳入以下四個參數。

  1. accumulator:累加器。
  2. currentValue:原陣列目前所迭代的元素。
  3. currentIndex 選擇性:原陣列目前所迭代處理中的元素之索引。若有傳入 initialValue,則由索引 0 之元素開始,若無則自索引 1 之元素開始。
  4. array 選擇性:呼叫 reduce() 方法的陣列。

initialValue 選擇性 - 用於設定累加器的初始值,如未設定,將會從第一個元素開始進行累加。

# 運行順序:

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

上述初始值設定為 10 ,所以在最初的運行時,累進器的值為 10 。