Array.prototype.toSorted()
Array
实例的 toSorted()
方法是 sort()
方法的 copying 版本。它返回一个新数组,其中元素按升序排序。
¥The toSorted()
method of Array
instances is the copying version of the sort()
method. It returns a new array with the elements sorted in ascending order.
语法
参数
返回值
描述
¥Description
有关 compareFn
参数的更多信息,请参阅 sort()
。
¥See sort()
for more information on the compareFn
parameter.
当在 稀疏数组 上使用时,toSorted()
方法会迭代空槽,就好像它们具有值 undefined
一样。
¥When used on sparse arrays, the toSorted()
method iterates empty slots as if they have the value undefined
.
toSorted()
方法是 generic。它只期望 this
值具有 length
属性和整数键控属性。
¥The toSorted()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
示例
对数组进行排序
¥Sorting an array
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]
更多使用示例请参见 sort()
。
¥For more usage examples, see sort()
.
在稀疏数组上使用 toSorted()
¥Using toSorted() on sparse arrays
空槽按其值为 undefined
进行排序。它们总是被排序到数组的末尾,并且不会为它们调用 compareFn
。
¥Empty slots are sorted as if they have the value undefined
. They are always sorted to the end of the array and compareFn
is not called for them.
console.log(["a", "c", , "b"].toSorted()); // ['a', 'b', 'c', undefined]
console.log([, undefined, "a", "b"].toSorted()); // ["a", "b", undefined, undefined]
对非数组对象调用 toSorted()
¥Calling toSorted() on non-array objects
toSorted()
方法读取 this
的 length
属性。然后,它收集 0
到 length - 1
范围内的所有现有整数键控属性,对它们进行排序,并将它们写入新数组。
¥The toSorted()
method reads the length
property of this
. It then collects all existing integer-keyed properties in the range of 0
to length - 1
, sorts them, and writes them into a new array.
const arrayLike = {
length: 3,
unrelated: "foo",
0: 5,
2: 4,
3: 3, // ignored by toSorted() since length is 3
};
console.log(Array.prototype.toSorted.call(arrayLike));
// [4, 5, undefined]
规范
Specification |
---|
ECMAScript Language Specification # sec-array.prototype.tosorted |
浏览器兼容性
BCD tables only load in the browser