萬盛學電腦網

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

JavaScript Array.sort() 完整指南:比較函數、數字/對象/多鍵排序、穩定性與性能

Array.prototype.sort() 是 JS 最常用的排序方法,但默認按 Unicode 字符串排序導致數字排序錯誤。本文系統講解比較函數編寫、數字/日期/對象/多字段排序、穩定排序保證、性能特徵與常見陷阱。

1. 默認行為:字符串 Unicode 排序

[2, 4, 8, 1, 22, 3].sort(); 
// [1, 2, 22, 3, 4, 8] — "22" < "3" (字符 '2' < '3')

2. 比較函數 核心規則

arr.sort(function compare(a, b) {
    // 返回 < 0 : a 排在 b 前
    // 返回 = 0 : 相對位置不變(穩定排序保證)
    // 返回 > 0 : b 排在 a 前
});

3. 常用比較函數模板

場景比較函數示例結果
數字升序(a,b)=>a-b[1,2,3,4,8,22]
數字降序(a,b)=>b-a[22,8,4,3,2,1]
日期升序(a,b)=>a.getTime()-b.getTime() 或 a-b早→晚
字符串本地化排序(a,b)=>a.localeCompare(b, 'zh-CN')拼音/筆畫序
對象按字段升序(a,b)=>a.field - b.field數字字段
對象按字段降序(a,b)=>b.field - a.field—
多字段:age↑, name↓(a,b)=>a.age-b.age || b.name.localeCompare(a.name)短路特性組合
空值/undefined 置後(a,b)=> (a==null)-(b==null) || a-bnull 最後

4. 實戰代碼片段

4.1 數字排序(修正原文錯誤示例)

var arr = [2,4,8,1,22,3];
var sorted = arr.slice().sort((a,b) => a - b); // 不改動原數組
console.log(sorted); // [1,2,3,4,8,22]
console.log(arr);    // [2,4,8,1,22,3] 原數組不變

4.2 對象數組多字段排序

var products = [
    {name:'Apple', price:10, category:'Fruit'},
    {name:'Banana', price:5, category:'Fruit'},
    {name:'Carrot', price:3, category:'Vegetable'}
];

// 類別升序,同類別價格降序
products.sort((a,b) => 
    a.category.localeCompare(b.category) || b.price - a.price
);

4.3 日期排序

var dates = ['2024-01-15', '2023-12-01', '2024-01-10'];
dates.sort((a,b) => new Date(a) - new Date(b)); // ISO 字符串可直接相減

5. 穩定排序保證 (ES2019+)

規範要求 sort 穩定:相等元素相對順序不變。現代瀏覽器(Chrome 70+, Firefox 60+, Safari 12+, Edge 79+)均已實現。舊環境需引入 Polyfill 或使用穩定排序庫。

6. 性能特徵

  • V8 使用 Timsort(歸併+插入混合),近乎已排序數組 O(n),隨機 O(n log n)。
  • 比較函數調用次數 ≈ n log n,保持比較函數極簡(避免複雜計算、對象創建)。
  • 大數組(>10萬)考慮 Web Worker 或分片排序避免阻塞主線程。

7. 避坑清單

  1. 忘記 return 比較函數 → 返回 undefined → 行為未定義。
  2. 比較函數返回布爾值 true/false → 隱式轉 1/0,邏輯錯誤。
  3. 直接排序原數組導致副作用 → 用 slice() 或 [...arr] 複製。
  4. 對象屬性可能缺失 → 比較函數內做兜底 (a?.field ?? 0) - (b?.field ?? 0)。

8. TypeScript 類型安全比較函數

type Comparator = (a: T, b: T) => number;

function byField(field: keyof T, dir: 'asc'|'desc' = 'asc'): Comparator {
    return (a, b) => {
        const av = a[field], bv = b[field];
        return dir === 'asc' ? (av > bv ? 1 : av < bv ? -1 : 0) 
                             : (av < bv ? 1 : av > bv ? -1 : 0);
    };
}

users.sort(byField('age', 'asc')); // 類型安全

掌握 sort(compareFn) 靈活組合比較邏輯,是處理列表展示、數據分析、表格排序的核心技能。

copyright © 萬盛學電腦網 all rights reserved