// 每日前端夜話 第471篇
// 正文共:1200 字
// 預計閱讀時間:7 分鐘除了普通對象之外,數組是 JavaScript 中使用最廣泛的數據結構。數組上最常使用的操作是按索引訪問元素。
本文介紹新的數組方法 array.at(index)。
新方法最主要好處是可以用負索引從數組末尾訪問元素,而平時使用的方括號語法 array[index] 則沒有辦法做到。
方括號語法的局限性通常按索引訪問數組元素的方法是使用方括號語法 array[index]:
const fruits = ['orange', 'apple', 'banana', 'grape'];
const item = fruits[1];
item; // => 'apple'表達式 array[index] 的執行結果是位於 index 位置的數組元素項,JavaScript 中數組的索引從 0 開始,這些你肯定知道。
通常方括號語法是一種通過正索引(>= 0)訪問數組元素的方法。它的語法簡單易讀。
但有時我們希望從末尾開始訪問元素。例如:
const fruits = ['orange', 'apple', 'banana', 'grape'];
const lastItem = fruits[fruits.length - 1];
lastItem; // => 'grape'fruits[fruits.length-1] 是訪問數組最後一個元素的方式,其中fruits.length-1 是最後一個元素的索引。
問題在於方括號不允許直接從數組末尾訪問元素,也不能接受負索引。
幸運的是,一項新的提案(截至2021年1月的第3階段) (https://github.com/tc39/proposal-relative-indexing-method)將 at() 方法引入了數組(以及類型化數組和字符串),並解決了方括號的許多限制。
array.at() 方法簡而言之,array.at(index) 用來訪問處於 index 位置的元素。
如果 index 是一個正整數 >= 0,則該方法返回這個索引位置的元素:
const fruits = ['orange', 'apple', 'banana', 'grape'];
const item = fruits.at(1);
item; // => 'apple'如果 index 參數大於或等於數組長度,則像方括號語法一樣返回 undefined:
const fruits = ['orange', 'apple', 'banana', 'grape'];
const item = fruits.at(999);
item; // => undefined當對 array.at() 方法使用負索引時,會從數組的末尾訪問元素。
例如用索引 -1 來訪問數組的最後一個元素:
const fruits = ['orange', 'apple', 'banana', 'grape'];
const lastItem = fruits.at(-1);
lastItem; // => 'grape'下面是更詳細的例子:
const vegetables = ['potatoe', 'tomatoe', 'onion'];
vegetables.at(0); // => 'potatoe'
vegetables.at(1); // => 'tomatoe'
vegetables.at(2); // => 'onion'
vegetables.at(3); // => undefined
vegetables.at(-1); // => 'onion'
vegetables.at(-2); // => 'tomatoe'
vegetables.at(-3); // => 'potatoe'
vegetables.at(-4); // => undefined如果 negIndex 是一個負索引 < 0,那麼 array.at(negIndex) 將會訪問位於索引 array.length + negIndex 處的元素。例如:
const fruits = ['orange', 'apple', 'banana', 'grape'];
const negIndex = -2;
fruits.at(negIndex); // => 'banana'
fruits[fruits.length + negIndex]; // => 'banana'
總結JavaScript 中的方括號語法是按索引訪問項目的常用方法。只需將索引表達式放在方括號 array[index] 中,然後既可以獲取在該索引處的數組項。
但是有時這種方式並不方便,因為它不接受負索引。所以要訪問數組的最後一個元素,需要用這種方法:
const lastItem = array[array.length - 1];新的數組方法 array.at(index) 使你可以將索引作為常規訪問器訪問數組元素。此外,array.at(index)接受負索引,在這種情況下,該方法從頭開始獲取元素:
const lastItem = array.at(-1);現在只需要把 array.prototype.at (https://github.com/es-shims/Array.prototype.at) polyfill 包含到你的應用程式中,就可以使用 array.at() 了。
強力推薦前端面試刷題神器
精彩文章回顧,點擊直達