Array.prototype.reduce() 是函數式編程中最強大、最基礎的高階函數之一,能將數組「歸約」為單一值。本文深入解析其語法、執行流程、Polyfill 實現、進階模式及實戰應用。
array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue)
| 參數 | 說明 |
|---|---|
| callback | 每個元素執行的函數,返回值作為下一次調用的 accumulator |
| accumulator | 累積器,上一次回調返回值;首次為 initialValue 或數組首元素 |
| currentValue | 當前處理的元素 |
| currentIndex | 當前元素索引 |
| array | 調用 reduce 的數組 |
| initialValue | 可選,初始累積值。省略時用數組首元素,且從索引 1 開始 |
// 無 initialValue: [1,2,3].reduce((a,b)=>a+b)
// 步驟1: a=1, b=2 → 3
// 步驟2: a=3, b=3 → 6
// 返回 6
// 有 initialValue: [1,2,3].reduce((a,b)=>a+b, 10)
// 步驟1: a=10, b=1 → 11
// 步驟2: a=11, b=2 → 13
// 步驟3: a=13, b=3 → 16
// 返回 16
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(callback /*, initialValue*/) {
if (this == null) throw new TypeError('Array.prototype.reduce called on null or undefined');
if (typeof callback !== 'function') throw new TypeError(callback + ' is not a function');
const len = this.length >>> 0;
let accumulator;
let startIndex = 0;
if (arguments.length >= 2) {
accumulator = arguments[1];
} else {
// 尋找第一個存在的元素作為初始值
while (startIndex < len && !(startIndex in this)) startIndex++;
if (startIndex >= len) throw new TypeError('Reduce of empty array with no initial value');
accumulator = this[startIndex++];
}
for (; startIndex < len; startIndex++) {
if (startIndex in this) {
accumulator = callback(accumulator, this[startIndex], startIndex, this);
}
}
return accumulator;
};
}
const sum = [1,2,3,4].reduce((a,b) => a+b, 0); // 10
const product = [1,2,3,4].reduce((a,b) => a*b, 1); // 24
const max = [5,2,8,1].reduce((a,b) => Math.max(a,b)); // 8 (無初始值)
const flat = [[1,2], [3,4], [5]].reduce((acc, val) => acc.concat(val), []);
// [1,2,3,4,5]
// 現代寫法: arr.flat() 或 [].concat(...arr)
const users = [
{name: 'Alice', role: 'admin'},
{name: 'Bob', role: 'user'},
{name: 'Charlie', role: 'admin'}
];
const byRole = users.reduce((acc, user) => {
(acc[user.role] = acc[user.role] || []).push(user);
return acc;
}, {});
// { admin: [{...}, {...}], user: [{...}] }
const data = {a:1, b:2, c:3};
const sum = Object.values(data).reduce((a,b) => a+b, 0); // 6
// 對象轉換
const mapped = Object.entries(data).reduce((acc, [k,v]) => {
acc[k+'_new'] = v * 2;
return acc;
}, {});
// {a_new:2, b_new:4, c_new:6}
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const add1 = x => x+1;
const double = x => x*2;
const square = x => x*x;
const compute = pipe(add1, double, square);
console.log(compute(3)); // ((3+1)*2)^2 = 64
// map
const map = (arr, fn) => arr.reduce((acc, v, i, a) => { acc.push(fn(v,i,a)); return acc; }, []);
// filter
const filter = (arr, fn) => arr.reduce((acc, v, i, a) => { if(fn(v,i,a)) acc.push(v); return acc; }, []);
// find
const find = (arr, fn) => arr.reduce((acc, v, i, a) => acc !== undefined ? acc : fn(v,i,a) ? v : acc, undefined);
// ❌ 錯誤
[1,2,3].reduce((a,b) => { a+b; }); // undefined
// ✅ 正確
[1,2,3].reduce((a,b) => a+b); // 6
[].reduce((a,b)=>a+b); // TypeError
[].reduce((a,b)=>a+b, 0); // 0 ✅
// ❌ 錯誤:並發執行而非串行
async function wrong() {
return await [1,2,3].reduce(async (acc, x) => {
return await acc + await asyncDouble(x);
}, 0);
}
// ✅ 正確:串行 await
async function correct() {
let acc = 0;
for (const x of [1,2,3]) {
acc += await asyncDouble(x);
}
return acc;
}
// ✅ 並發併發控制:Promise.all + map
async function concurrent() {
return (await Promise.all([1,2,3].map(asyncDouble))).reduce((a,b)=>a+b, 0);
}
reduce:從左到右 (索引 0 → length-1)reduceRight:從右到左 (索引 length-1 → 0)
<html>
<head><title>JavaScript Array reduce Method</title></head>
<body>
<script>
var total = [0, 1, 2, 3].reduce(function(a, b) { return a + b; });
document.write("total is : " + total); // 6
</script>
</body>
</html>
reduce() 是數組操作的「終極武器」,掌握其累積器模式可構建任意數據轉換邏輯。核心要點:
accumulator 流轉機制initialValue 避免空數組報錯、明確初始狀態