Array.prototype.at()

Baseline 已广泛支持

此特性已经十分成熟,可在许多设备和浏览器版本上使用。自 2022 年 3 月起,它已在各浏览器中可用。

at() 方法用于 Array 实例,它接受一个整数值并返回该索引处的项,支持正整数和负整数。负整数从数组的最后一个项开始倒计数。

试一试

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

数组元素的零基索引,转换为整数。负数索引从数组末尾开始倒计数 — 如果 index < 0,则访问 index + array.length

返回值

与给定索引匹配的数组元素。如果 index < -array.lengthindex >= 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() 方法读取 thislength 属性并计算要访问的索引。

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

浏览器兼容性

另见