在 JavaScript 的陣列方法中,reduce 常被視為最強大也最容易被忽略的一個。它能夠把整個陣列「壓縮」成單一結果,無論是求和、拼接字串還是物件聚合,都能靠它優雅完成。本文將從語法結構、回調參數、邊界情況一路講到 reduceRight 的差異,並搭配可運行的範例。
基本語法如下:
array1.reduce(callbackfn[, initialValue])
previousValue 傳入,而不是陣列的第一個元素。回傳值是「最後一次呼叫回調所得到的累加結果」。以下兩種情況會拋出 TypeError:
callbackfn 不是函數物件。initialValue。function callbackfn(previousValue, currentValue, currentIndex, array1)
previousValue:上一次回調的返回值;若設定了初始值,首次呼叫時它就是該初始值。currentValue:目前處理到的陣列元素。currentIndex:目前元素的索引編號。array1:被呼叫 reduce 的陣列本身。這裡是最容易混淆的環節,關鍵取決於有沒有傳初始值:
有傳 initialValue:
previousValue = initialValuecurrentValue = 陣列第一個元素沒傳 initialValue:
previousValue = 陣列第一個元素currentValue = 陣列第二個元素回調函數裡是可以動到原陣列的,但行為需要留意。下表整理了几種常見情形:
由於沒有傳初始值,第一次呼叫時 previousValue 是 "abc",currentValue 是 "def"。
function appendCurrent(previousValue, currentValue) {
return previousValue + "::" + currentValue;
}
var elements = ["abc", "def", 123, 456];
var result = elements.reduce(appendCurrent);
document.write(result); // abc::def::123::456
function addRounded(previousValue, currentValue) {
return previousValue + Math.round(currentValue);
}
var numbers = [10.9, 15.4, 0.5];
var result = numbers.reduce(addRounded, 0);
document.write(result); // 27
function addDigitValue(previousValue, currentDigit, currentIndex, array) {
var exponent = (array.length - 1) - currentIndex;
var digitValue = currentDigit * Math.pow(10, exponent);
return previousValue + digitValue;
}
var digits = [4, 1, 2, 5];
var result = digits.reduce(addDigitValue, 0);
document.write(result); // 4125
解題思路:因為初始值是 0,所以 currentDigit 會從 4 開始,總共呼叫四次,四次傳入的參數組我可以逐一列出來:
(0, 4, 0, array) (4, 1, 1, array) (1, 2, 2, array) (2, 5, 3, array)
由於起始值為 0,實際上只要把每次回調的返回值相加即可。array.length 全程固定為 4,因此四次分別算出 4000、100、20、5,合計 4125。
reduceRight 的語法與回調參數定義和 reduce 完全一致,唯一的差別在於走訪方向:
reduce 由索引 0 往後走(升序)。reduceRight 由 arr.length - 1 往前走(降序)。因此,有初始值時它會從最後一個元素開始累加;沒有初始值時,previousValue 是陣列最後一個元素,currentValue 則是倒數第二個元素。
初始值給一個空陣列,逐筆把符合條件的元素串接起來。
function Process2(previousArray, currentValue) {
var nextArray;
if (currentValue >= 1 && currentValue <= 10) nextArray = previousArray.concat(currentValue);
else nextArray = previousArray;
return nextArray;
}
var numbers = [20, 1, -5, 6, 50, 3];
var emptyArray = new Array();
var resultArray = numbers.reduceRight(Process2, emptyArray);
document.write("result array=" + resultArray); // result array=3,6,1
因為是從右往左走,結果的順序自然是 3、6、1。
字串雖然不是陣列,但可以透過 call 借用陣列原型上的方法。
function AppendToArray(previousValue, currentValue) {
return previousValue + currentValue;
}
var word = "retupmoc";
var result = [].reduceRight.call(word, AppendToArray, "the ");
// 也可以寫成 Array.prototype.reduceRight.call(word, AppendToArray, "the ");
document.write(result); // the computer
這裡有兩種等效寫法:用空陣列去呼叫 reduceRight 並以 call 注入參數,或者直接走原型鏈 Array.prototype.reduceRight.call(...)。兩者效果相同,後者語意更明確一些。
多數場景下兩者可以互換,但當「順序本身就是業務邏輯」時,方向就變得很關鍵。例如拼接階層路徑、解析巢狀結構、或像範例二那樣反轉字元序列,reduceRight 能省掉一次額外的反轉操作。反過來,累加總和、扁平化陣列這類運算則用 reduce 更直覺。