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

瀏覽器相容性

另見