试一试
const array = [5, 12, 8, 130, 44];
let index = 2;
console.log(`An index of ${index} returns ${array.at(index)}`);
// Expected output: "An index of 2 returns 8"
index = -2;
console.log(`An index of ${index} returns ${array.at(index)}`);
// Expected output: "An index of -2 returns 130"
语法
js
at(index)
参数
返回值
与给定索引匹配的数组元素。如果 index < -array.length 或 index >= array.length,则始终返回 undefined,而不尝试访问相应的属性。
描述
当 index 是非负整数时,at() 方法等同于方括号表示法。例如,array[0] 和 array.at(0) 都返回第一个项。但是,当从数组末尾开始计数元素时,您不能像在 Python 或 R 中那样使用 array[-1],因为方括号内的所有值都被视为字面上的字符串属性,所以最终会读取 array["-1"],这只是一个普通的字符串属性,而不是数组索引。
通常的做法是访问 length 并据此计算索引 — 例如,array[array.length - 1]。at() 方法允许相对索引,因此可以将其缩短为 array.at(-1)。
通过将 at() 与 with() 结合使用,您可以使用负数索引来读取和写入(分别)数组。
at() 方法是 通用的。它只期望 this 值具有 length 属性和整数键属性。
示例
返回数组的最后一个值
以下示例提供了一个函数,该函数返回指定数组中找到的最后一个元素。
js
// Our array with items
const cart = ["apple", "banana", "pear"];
// A function which returns the last item of a given array
function returnLast(arr) {
return arr.at(-1);
}
// Get the last item of our array 'cart'
const item1 = returnLast(cart);
console.log(item1); // 'pear'
// Add an item to our 'cart' array
cart.push("orange");
const item2 = returnLast(cart);
console.log(item2); // 'orange'
比较方法
此示例比较了选择 Array 中倒数第二个(倒数第一个之前)项的不同方法。尽管下面显示的所有方法都是有效的,但此示例突出了 at() 方法的简洁性和可读性。
js
// Our array with items
const colors = ["red", "green", "blue"];
// Using length property
const lengthWay = colors[colors.length - 2];
console.log(lengthWay); // 'green'
// Using slice() method. Note an array is returned
const sliceWay = colors.slice(-2, -1);
console.log(sliceWay[0]); // 'green'
// Using at() method
const atWay = colors.at(-2);
console.log(atWay); // 'green'
在非数组对象上调用 at()
at() 方法读取 this 的 length 属性并计算要访问的索引。
js
const arrayLike = {
length: 2,
0: "a",
1: "b",
2: "c", // ignored by at() since length is 2
};
console.log(Array.prototype.at.call(arrayLike, 0)); // "a"
console.log(Array.prototype.at.call(arrayLike, 2)); // undefined
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-array.prototype.at |
浏览器兼容性
加载中…