array.prototype.tosorted 不修改原数组,始终返回新数组。它为纯函数式方法,无论是否传入比较函数,原始数组的顺序、引用和内容均保持不变,是 es2024 新增的安全排序 api。

Array.prototype.toSorted 本身就不会破坏原始数组,它总是返回一个新数组,原始数组保持不变。所以“不破坏原始排序”是它的默认行为,无需额外操作。
toSorted 的核心特性
与 sort() 方法不同,toSorted() 是纯函数式方法:
- 不修改原数组,始终返回新数组
- 原数组的顺序、引用、内容完全不变
- 即使传入比较函数,也不会影响原始数据
基本用法示例
直接调用即可安全获得排序结果:
const original = [3, 1, 4, 1, 5];const sorted = original.toSorted(); // [1, 1, 3, 4, 5]
console.log(original); // [3, 1, 4, 1, 5] ← 未改变
自定义排序也不影响原数组
按字符串长度、对象属性等排序时,同样安全:
const words = ['banana', 'apple', 'kiwi'];const byLength = words.toSorted((a, b) => a.length - b.length); // ['kiwi', 'apple', 'banana']
console.log(words); // ['banana', 'apple', 'kiwi'] ← 原序保留
兼容性与替代方案
toSorted 是较新的 API(ES2024),如需支持旧环境:
- 可用 [...arr].sort() 模拟(注意:需手动传入比较函数才能稳定排序)
- 避免直接用 arr.sort(),否则会改写原数组
- TypeScript 中需确保 lib 设置包含 es2024 或更高版本










