1. 程式人生 > 其它 >陣列將要新增的方法:array.at(index)

陣列將要新增的方法:array.at(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階段)將 at() 方法引入了陣列(以及型別化陣列和字串),並解決了方括號的許多限制。

https://www.51220.cn 51220網站目錄

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 polyfill 包含到你的應用程式