Array.prototype.toReversed()
Baseline 2023
Newly available
Since July 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.
Array
实例的 toReversed()
方法是 reverse()
方法的 copying 对应方法。它返回一个新数组,其中元素的顺序相反。
¥The toReversed()
method of Array
instances is the copying counterpart of the reverse()
method. It returns a new array with the elements in reversed order.
语法
参数
返回值
描述
¥Description
toReversed()
方法以相反的顺序转置调用数组对象的元素并返回一个新数组。
¥The toReversed()
method transposes the elements of the calling array object in reverse order and returns a new array.
当在 稀疏数组 上使用时,toReversed()
方法会迭代空槽,就好像它们具有值 undefined
一样。
¥When used on sparse arrays, the toReversed()
method iterates empty slots as if they have the value undefined
.
toReversed()
方法是 generic。它只期望 this
值具有 length
属性和整数键控属性。
¥The toReversed()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
示例
反转数组中的元素
¥Reversing the elements in an array
以下示例创建一个包含三个元素的数组 items
,然后创建一个与 items
相反的新数组。items
数组保持不变。
¥The following example creates an array items
, containing three elements, then creates a new array that's the reverse of items
. The items
array remains unchanged.
const items = [1, 2, 3];
console.log(items); // [1, 2, 3]
const reversedItems = items.toReversed();
console.log(reversedItems); // [3, 2, 1]
console.log(items); // [1, 2, 3]
在稀疏数组上使用 toReversed()
¥Using toReversed() on sparse arrays
toReversed()
的返回值永远不会稀疏。返回数组中的空槽变为 undefined
。
¥The return value of toReversed()
is never sparse. Empty slots become undefined
in the returned array.
console.log([1, , 3].toReversed()); // [3, undefined, 1]
console.log([1, , 3, 4].toReversed()); // [4, 3, undefined, 1]
对非数组对象调用 toReversed()
¥Calling toReversed() on non-array objects
toReversed()
方法读取 this
的 length
属性。然后,它按降序访问具有 length - 1
和 0
之间整数键的每个属性,将当前属性的值添加到要返回的数组的末尾。
¥The toReversed()
method reads the length
property of this
. It then visits each property having an integer key between length - 1
and 0
in descending order, adding the value of the current property to the end of the array to be returned.
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
console.log(Array.prototype.toReversed.call(arrayLike));
// [4, undefined, undefined]
// The '0' and '1' indices are not present so they become undefined
规范
Specification |
---|
ECMAScript Language Specification # sec-array.prototype.toreversed |
浏览器兼容性
BCD tables only load in the browser