萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript reduce() 方法深度解析:從數組歸約到函數式編程核心

前言

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

三、Polyfill 實現 (兼容舊環境)


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;
    };
}

四、核心用法示例

1. 求和/乘積/統計


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 (無初始值)

2. 數組扁平化 (一維)


const flat = [[1,2], [3,4], [5]].reduce((acc, val) => acc.concat(val), []);
// [1,2,3,4,5]
// 現代寫法: arr.flat() 或 [].concat(...arr)

3. 分組統計 (對象累積器)


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: [{...}] }

4. 對象屬性提取/轉換


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}

5. 函數組合 (管道操作)


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

6. 實現 map/filter/find 等方法


// 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:忘記返回累積器


// ❌ 錯誤
[1,2,3].reduce((a,b) => { a+b; }); // undefined

// ✅ 正確
[1,2,3].reduce((a,b) => a+b); // 6

⚠️ 陷阱 2:空數組無初始值拋錯


[].reduce((a,b)=>a+b); // TypeError
[].reduce((a,b)=>a+b, 0); // 0 ✅

⚠️ 陷阱 3:異步操作不可直接在 reduce 中 await


// ❌ 錯誤:並發執行而非串行
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 vs reduceRight

  • 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() 是數組操作的「終極武器」,掌握其累積器模式可構建任意數據轉換邏輯。核心要點:

  1. 理解 accumulator 流轉機制
  2. 善用 initialValue 避免空數組報錯、明確初始狀態
  3. 返回新累積器而非修改原值 (函數式純粹性)
  4. 異步場景改用 for...of 或 Promise.all
  5. 性能敏感場景簡單循環可能更快,但 reduce 表達力更強
copyright © 萬盛學電腦網 all rights reserved