萬盛學電腦網

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

jQuery Tablesorter 中文排序與大數值精度問題解決方案

問題一:中文排序無效

Tablesorter 默認使用 Unicode 碼點比較字符串,導致中文拼音順序錯誤。

原始比較函數

function sortText(a, b) {
    return (a < b) ? -1 : (a > b) ? 1 : 0;
}

解決方案:localeCompare

function sortText(a, b) {
    return a.localeCompare(b);        // 升序:按當前語言環境(中文拼音)比較
}
function sortTextDesc(a, b) {
    return b.localeCompare(a);        // 降序
}

localeCompare 根據瀏覽器語言環境進行字符串比較,完美支持中文拼音排序。注意:無法處理多音字(按首個讀音排序)。

問題二:大數值精度丟失導致排序錯誤

JavaScript Number 型為 IEEE 754 雙精度浮點,安全整數範圍 ±253-1(約 9×1015)。超出範圍的整數會丟失精度:

parseFloat('9999999999999999')  // 10000000000000000
parseFloat('10000000000000001') // 10000000000000000 (相等!)
parseFloat('10000000000000004') // 10000000000000004
parseFloat('10000000000000005') // 10000000000000004 (又相等!)

導致大數值排序順序錯誤。

解決方案:權值比較法(不轉數值)

將數值視為字符串,按位權重比較:

function compareBigNumber(a, b) {
    // 統一長度(左側補零)
    const maxLen = Math.max(a.length, b.length);
    a = a.padStart(maxLen, '0');
    b = b.padStart(maxLen, '0');
    // 逐位比較
    for (let i = 0; i < maxLen; i++) {
        if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
    }
    return 0;
}

// 整合到 Tablesorter parser
$.tablesorter.addParser({
    id: 'bigNumber',
    is: (s) => /^\d+$/.test(s) && s.length > 15, // 超過安全長度
    format: (s) => s, // 保持字符串
    type: 'text',     // 使用文本比較器
    // 或自定義比較器
    // comparator: (a, b) => compareBigNumber(a, b)
});

完整集成示例

$(document).ready(function() {
    $("#myTable").tablesorter({
        headers: {
            0: { sorter: 'text' },      // 中文列用 localeCompare
            3: { sorter: 'bigNumber' }  // 大數值列用字符串比較
        },
        textSorter: function(a, b, direction) {
            // 全局文本排序器,自動處理中文
            return direction ? b.localeCompare(a) : a.localeCompare(b);
        }
    });
});

現代替代:原生 JS 表格排序

參考前文「表格排序通用組件」,無依賴、體積小、完全可控,推薦新項目使用。

copyright © 萬盛學電腦網 all rights reserved