大网数据广告活动
Web 标准与前端开发

Array.prototype.toSorted()

· 52CE 我爱测

Array 实例的 **`toSorted()`** 方法是 Array/sort 方法的复制方法版本。它返回一个新数组,其元素按升序排列。

Array 实例的 toSorted() 方法是 Array/sort 方法的复制方法版本。它返回一个新数组,其元素按升序排列。

语法

// 不传入函数
toSorted()

// 传入箭头函数
toSorted((a, b) => { /* … */ })

// 传入比较函数
toSorted(compareFn)

// 内联比较函数
toSorted(function compareFn(a, b) { /* … */ })

参数

  • compareFn
    • : 指定一个定义排序顺序的函数。如果省略,则将数组元素转换为字符串,然后根据每个字符的 Unicode 码位值进行排序。
      • a
        • : 用于比较的第一个元素。
      • b
        • : 用于比较的第二个元素。

返回值

一个新数组,其元素按升序排序。

描述

有关 compareFn 参数的更多信息,请参阅 Array/sort。

当在稀疏数组上使用 toSorted() 方法时,它迭代时会将空槽视为具有 undefined 值的元素。

toSorted() 方法是通用的,它只期望 this 值具有 length 属性和整数键属性。

示例

对数组进行排序

const months = ["Mar", "Jan", "Feb", "Dec"];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']
console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']

const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b);
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]

有关更多用法示例,请参见 Array/sort。

在稀疏数组上使用 toSorted()

空槽被视为具有 undefined 值而被排序。它们总是排序到数组的末尾,并且 compareFn 不会对它们进行调用。

console.log(["a", "c", , "b"].toSorted()); // ['a', 'b', 'c', undefined]
console.log([, undefined, "a", "b"].toSorted()); // ["a", "b", undefined, undefined]

在非数组对象上调用 toSorted()

toSorted() 方法会读取 this 的 length 属性。然后它会收集所有在 0 到 length - 1 范围内的整数键属性,对它们进行排序并将它们写入一个新的数组中。

const arrayLike = {
  length: 3,
  unrelated: "foo",
  0: 5,
  2: 4,
};
console.log(Array.prototype.toSorted.call(arrayLike));
// [4, 5, undefined]

规范

浏览器兼容性

参见

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。