← 中文资源

简体中文版本

不带比较器的 sort 按字符串排序

默认 sort 把元素转成字符串按码元比较,数字会按字典序排列;数值排序必须传比较器,字符串按语言习惯用 localeCompare,undefined 一律沉底,sort 原地修改数组。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

default : 100,25,3,80,9
numeric : 3,9,25,80,100
names default      : Bea,Zoe,adam
names localeCompare: adam,Bea,Zoe
undefined sinks: 1,3,undefined,undefined
sorted copy: 3,9,25,80,100 | original intact: 80,9,100,25,3

实现说明

各个操作都建立在顶层绑定之上:scores、names、withUndefined、sorted。

使用要点

  • 演示输出是带标签的(default :、numeric :、names localeCompare:),每个操作都会留下自己的一行标注。

常见问题

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。 状态都挂在模块顶层:scores、names、withUndefined。

核心语句

const sorted = scores.slice().sort((a, b) => a - b);

代码示例

// sort without a comparator converts elements to strings and compares UTF-16 code units:
// numbers order lexicographically, not numerically
const scores = [80, 9, 100, 25, 3];
console.log('default :', scores.slice().sort().join(','));
console.log('numeric :', scores.slice().sort((a, b) => a - b).join(','));

// String arrays: default order is by code unit (uppercase before lowercase), localeCompare follows language rules
const names = ['Zoe', 'adam', 'Bea'];
console.log('names default      :', names.slice().sort().join(','));
console.log('names localeCompare:', names.slice().sort((a, b) => a.localeCompare(b)).join(','));

// undefined is exempt from comparison: any comparator sends it to the end of the array
const withUndefined = [3, undefined, 1, undefined];
console.log(
  'undefined sinks:',
  withUndefined.slice().sort((a, b) => a - b).map((v) => String(v)).join(','),
);

// sort mutates the array in place: slice() first when the original must survive
const sorted = scores.slice().sort((a, b) => a - b);
console.log('sorted copy:', sorted.join(','), '| original intact:', scores.join(','));