实现说明
各个操作都建立在顶层绑定之上: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(','));