萬盛學電腦網

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

jQuery 聚合函數擴充:實作 aggregate、count 等集合操作

前言

jQuery 核心未內建集合聚合運算 (如 sum, avg, count, min, max)。本文展示如何擴充 jQuery 原型,實作靈活的 .aggregate() 基礎方法,並衍生出 .count()、.sum()、.max() 等實用聚合函式,提升資料處理表達力。

核心:aggregate 通用聚合器


;(function($) {
    /**
     * 通用聚合運算
     * @param {*} seed - 初始值 (累加器起始值)
     * @param {Function} func - 累加函式 (accumulator, element, index) => newAccumulator
     * @returns {*} 累加結果
     */
    $.fn.aggregate = function(seed, func) {
        if (typeof func !== 'function') {
            throw new TypeError('$.fn.aggregate 第二參數必須為函式');
        }
        
        let accumulator = seed;
        this.each(function(index, element) {
            accumulator = func(accumulator, element, index);
        });
        return accumulator;
    };
})(jQuery);

衍生實用聚合方法


;(function($) {
    // 計數
    $.fn.count = function() {
        return this.aggregate(0, (count) => count + 1);
    };

    // 求和:需指定取值函式
    $.fn.sum = function(getter) {
        const fn = typeof getter === 'function' ? getter : 
                   typeof getter === 'string' ? el => $(el).data(getter) :
                   el => +$(el).text() || +$(el).val() || 0;
        return this.aggregate(0, (sum, el) => sum + fn(el));
    };

    // 平均
    $.fn.avg = function(getter) {
        const count = this.length;
        return count ? this.sum(getter) / count : 0;
    };

    // 最大值
    $.fn.max = function(getter) {
        const fn = typeof getter === 'function' ? getter : 
                   el => +$(el).text() || +$(el).val() || -Infinity;
        return this.aggregate(-Infinity, (max, el) => Math.max(max, fn(el)));
    };

    // 最小值
    $.fn.min = function(getter) {
        const fn = typeof getter === 'function' ? getter : 
                   el => +$(el).text() || +$(el).val() || Infinity;
        return this.aggregate(Infinity, (min, el) => Math.min(min, fn(el)));
    };

    // 分組計數
    $.fn.groupCount = function(keyGetter) {
        const fn = typeof keyGetter === 'function' ? keyGetter : 
                   el => $(el).data(keyGetter) || $(el).attr(keyGetter) || $(el).text();
        return this.aggregate({}, (groups, el) => {
            const key = fn(el);
            groups[key] = (groups[key] || 0) + 1;
            return groups;
        });
    };

    // 分組求和
    $.fn.groupSum = function(keyGetter, valueGetter) {
        const kFn = typeof keyGetter === 'function' ? keyGetter : el => $(el).data(keyGetter);
        const vFn = typeof valueGetter === 'function' ? valueGetter : el => +$(el).data(valueGetter) || 0;
        return this.aggregate({}, (groups, el) => {
            const key = kFn(el);
            groups[key] = (groups[key] || 0) + vFn(el);
            return groups;
        });
    };
})(jQuery);

實戰應用範例

HTML 結構


<table id="sales-table">
    <thead>
        <tr><th>業務</th><th>產品</th><th>金額</th><th>季度</th></tr>
    </thead>
    <tbody>
        <tr data-salesperson="王小明" data-product="A" data-amount="12000" data-quarter="Q1"><td>王小明</td><td>產品A</td><td>12,000</td><td>Q1</td></tr>
        <tr data-salesperson="王小明" data-product="B" data-amount="8000" data-quarter="Q1"><td>王小明</td><td>產品B</td><td>8,000</td><td>Q1</td></tr>
        <tr data-salesperson="李大華" data-product="A" data-amount="15000" data-quarter="Q1"><td>李大華</td><td>產品A</td><td>15,000</td><td>Q1</td></tr>
        <tr data-salesperson="李大華" data-product="C" data-amount="9000" data-quarter="Q2"><td>李大華</td><td>產品C</td><td>9,000</td><td>Q2</td></tr>
        <tr data-salesperson="陳美美" data-product="B" data-amount="20000" data-quarter="Q2"><td>陳美美</td><td>產品B</td><td>20,000</td><td>Q2</td></tr>
    </tbody>
</table>

<div id="stats"></div>

統計計算


const $rows = $('#sales-table tbody tr');

// 1. 總筆數
console.log('總筆數:', $rows.count()); // 5

// 2. 總銷售額
console.log('總金額:', $rows.sum(el => +$(el).data('amount'))); // 64000

// 3. 平均單筆金額
console.log('平均金額:', $rows.avg(el => +$(el).data('amount'))); // 12800

// 4. 最高/最低單筆
console.log('最高單筆:', $rows.max(el => +$(el).data('amount'))); // 20000
console.log('最低單筆:', $rows.min(el => +$(el).data('amount'))); // 8000

// 5. 各業務筆數分組
console.log('業務分組:', $rows.groupCount('salesperson')); 
// { "王小明": 2, "李大華": 2, "陳美美": 1 }

// 6. 各業務總銷售額分組
console.log('業務業績:', $rows.groupSum('salesperson', 'amount'));
// { "王小明": 20000, "李大華": 24000, "陳美美": 20000 }

// 7. 顯示統計卡片
$('#stats').html(`
    
總筆數: ${$rows.count()}
總金額: ${$rows.sum(el => +$(el).data('amount')).toLocaleString()}
平均單筆: ${$rows.avg(el => +$(el).data('amount')).toFixed(0)}
`);

進階:鏈式呼叫與延遲執行


// 支援鏈式:回傳 jQuery 物件而非純值
$.fn.aggregateChain = function(seed, func, resultKey = 'aggregateResult') {
    const result = this.aggregate(seed, func);
    return this.data(resultKey, result); // 存入 data 供後續取用
};

// 使用
$('#sales-table tbody tr')
    .aggregateChain(0, (sum, el) => sum + $(el).data('amount'), 'totalAmount')
    .aggregateChain({}, (groups, el) => {
        const k = $(el).data('salesperson');
        groups[k] = (groups[k] || 0) + 1;
        return groups;
    }, 'salespersonCount')
    .each(function() {
        const $this = $(this);
        console.log('總金額:', $this.data('totalAmount'));
        console.log('人員統計:', $this.data('salespersonCount'));
    });

效能考量與最佳化

場景建議
大量元素 (1000+) 避免在 each 中重複建立 jQuery 物件 $(el),直接用 el.dataset.xxx 或原生屬性
頻繁計算 快取結果,避免重複 aggregate
數值轉換 預先在 data-* 存數值型別,或用 Number() 而非 parseInt()
記憶體 大量資料考慮用純陣列運算而非 jQuery 物件集合

現代替代方案:原生 JS + Lodash / Ramda


// 原生陣列 reduce (效能最佳,無依賴)
const rows = [...document.querySelectorAll('#sales-table tbody tr')];
const total = rows.reduce((sum, el) => sum + Number(el.dataset.amount), 0);
const byPerson = rows.reduce((groups, el) => {
    const name = el.dataset.salesperson;
    groups[name] = (groups[name] || 0) + Number(el.dataset.amount);
    return groups;
}, {});

// Lodash (函數式工具庫)
import _ from 'lodash';
const total = _.sumBy(rows, 'dataset.amount'); // 需轉換
const byPerson = _.groupBy(rows, 'dataset.salesperson');

總結

jQuery 聚合擴充以 .aggregate(seed, func) 為核心,衍生出 count, sum, avg, max, min, groupCount, groupSum 等實用方法,讓 DOM 集合具備類 SQL/LINQ 的查詢能力。適用於:表格統計、購物車試算、儀表板即時計算、表單驗證彙總。現代專案建議改用原生 Array.reduce 或工具庫,效能更好且無依賴。

copyright © 萬盛學電腦網 all rights reserved