JavaScript Array at() 方法
示例
獲取 fruits 的第三個元素
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.at(2);
自己動手試一試 »
獲取 fruits 的第三個元素
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[2];
自己動手試一試 »
更多示例見下文。
描述
at()
方法返回陣列中指定索引的元素。
at()
方法返回與 []
相同的結果。
at()
方法自 2022 年 3 月起在所有現代瀏覽器中受支援
注意
許多語言允許使用 負括號索引
,例如 [-1],來訪問物件/陣列/字串末尾的元素。
這在 JavaScript 中是不可能的,因為 [] 用於訪問陣列和物件。obj[-1] 指的是鍵 -1 的值,而不是物件的最後一個屬性。
at()
方法在 ES2022 中引入,旨在解決此問題。
語法
array.at(index)
引數
引數 | 描述 |
index | 可選。 要返回的陣列元素的索引(位置)。 預設值為 0。 -1 返回最後一個元素。 |
返回值
型別 | 描述 |
元素 | 陣列中給定位置(索引)的元素。 |
瀏覽器支援
JavaScript Array at()
自 2022 年 3 月起在所有瀏覽器中受支援
Chrome 92 | Edge 92 | Firefox 90 | Safari 15.4 | Opera 78 |
2021 年 4 月 | 2021 年 7 月 | 2021 年 7 月 | 2022 年 3 月 | 2021 年 8 月 |
更多示例
獲取 fruits 的第一個元素
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.at();
自己動手試一試 »
獲取 fruits 的最後一個元素
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.at(-1);
自己動手試一試 »