Get to know MDN better
此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
reduce() 方法將一個累加器及陣列中每項元素(由左至右)傳入回呼函式,將陣列化為單一值。
用於處理陣列中每個元素的函式,可傳入四個參數:
accumulator用來累積回呼函式回傳值的累加器(accumulator)或 initialValue(若有提供的話,詳如下敘)。累加器是上一次呼叫後,所回傳的累加數值。
currentValue原陣列目前所迭代處理中的元素。
currentIndex 選擇性原陣列目前所迭代處理中的元素之索引。若有傳入 initialValue,則由索引 0 之元素開始,若無則自索引 1 之元素開始。
array 選擇性呼叫 reduce() 方法的陣列。
initialValue 選擇性於第一次呼叫 callback 時要傳入的累加器初始值。若沒有提供初始值,則原陣列的第一個元素將會被當作初始的累加器。假如於一個空陣列呼叫 reduce() 方法且沒有提供累加器初始值,將會發生錯誤。
簡化後的結果值。
reduce() 會對每一個目前迭代到的陣列元素(除了空值以外)執行 callback 函式,回呼函式會接收四個參數:
當回呼函式第一次被呼叫時,accumulator 與 currentValue 的值可能為兩種不同的狀況:若在呼叫 reduce() 時有提供 initialValue,則 accumulator 將會等於 initialValue,且 currentValue 會等於陣列中的第一個元素值;若沒有提供 initialValue,則 accumulator 會等於陣列的第一個元素值,且 currentValue 將會等於陣列的第二個元素值。
備註:假如 initialValue 未被提供,reduce() 將會跳過第一個陣列索引,從陣列索引 1 開始執行回呼函式。若有提供 initialValue,則會由陣列索引 0 開始執行。
若陣列為空且沒有提供 initialValue,將會拋出 TypeError。假如陣列只有一個元素(無論其索引位置為何)並且沒有提供 initialValue,或如果提供了 initialValue 但陣列為空,則此唯一的值將會被直接回傳而不會呼叫 callback 函式。
提供累加器初始值通常較為安全,因為在沒有傳入 initialValue 的情況下會有三種可能的輸出結果,如下列範例:
假設 reduce() 以下例方式使用:
所傳入的回呼函式將被呼叫四次,所傳入的參數與回傳值如下所示:
| first call | 0 | 1 | 1 | [0, 1, 2, 3, 4] | 1 |
| second call | 1 | 2 | 2 | [0, 1, 2, 3, 4] | 3 |
| third call | 3 | 3 | 3 | [0, 1, 2, 3, 4] | 6 |
| fourth call | 6 | 4 | 4 | [0, 1, 2, 3, 4] | 10 |
reduce() 的最終回傳值將會是最後一次呼叫回呼函式的回傳值 (10)。
你也可以傳入一個箭頭函式來替代一個完整的函式。下方的程式碼執行的結果將與前述例子相同。
如果你有提供第二個參數值給 reduce(),執行的結果如下:
| 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 |
reduce() 執行的結果將會是 20。
另外,也可以寫成箭頭函式:
另外,也可以寫成箭頭函式:
如果還需要支援老舊到不支援 Object.defineProperty 的 JavaScript 引擎,最好不要 polyfill Array.prototype 方法,因為你無法令其不可枚舉(non-enumerable)。
| ECMAScript® 2027 Language Specification # sec-array.prototype.reduce |
Enable JavaScript to view this browser compatibility table.
This page was last modified on 2026年3月18日 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.