// main.js —— sort 的两个坑:默认按字符串比较、原地修改 // 结论全部来自真实调用。 export function defaultSortNumbers() { const nums = [10, 1, 5, 2]; const returned = nums.sort(); return { sorted: [...nums], sameReference: returned === nums, firstElement: nums[0], }; } export function numericSort() { const nums = [10, 1, 5, 2]; return [...nums].sort((a, b) => a - b); } export function numericSortMutates() { const nums = [10, 1, 5, 2]; nums.sort((a, b) => a - b); return nums; } export function stringCodeUnitOrder() { const words = ['b', 'A', 'a', 'B']; return [...words].sort(); } export function stableSort() { const rows = [ { k: 1, v: 'a' }, { k: 0, v: 'b' }, { k: 1, v: 'c' }, { k: 0, v: 'd' }, ]; return rows.sort((x, y) => x.k - y.k).map((r) => r.v); } export function nonMutatingAlternatives() { const nums = [3, 1, 2]; const sorted = nums.toSorted((a, b) => a - b); const reversed = nums.toReversed(); return { nums, sorted, reversed }; } export function run(log = console.log) { const d = defaultSortNumbers(); const rows = [ ['默认 sort:[10,1,5,2]', JSON.stringify(d.sorted)], ['sort 返回同一引用', String(d.sameReference)], ['数字比较器排序', JSON.stringify(numericSort())], ['sort 原地修改原数组', JSON.stringify(numericSortMutates())], ['字符串默认按 UTF-16 码元', JSON.stringify(stringCodeUnitOrder())], ['稳定排序(同键保持原顺序)', JSON.stringify(stableSort())], ['toSorted / toReversed 不改原数组', JSON.stringify(nonMutatingAlternatives())], ]; log('场景 => 结果'); for (const [label, value] of rows) log(`${label} => ${value}`); log('-'.repeat(50)); log('要点:sort 默认把元素转成字符串按码元比较,且原地排序;数字排序必须传 (a,b)=>a-b。'); return rows; }