1.方括號語法的局限性
通過索引訪問陣列元素一般使用方括號array[index]:
const fruits = ['orange', 'apple', 'banana', 'grape'];
const item = fruits[1];
item; // => 'apple'
運算式array[index]求值為位于index的陣列項,這種方式也叫屬性訪問器,
在大多數情況下,方括號語法是通過正索引(>= 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()方法引入了陣列(以及型別化的陣列和字串),并解決了方括號訪問器的諸多限制,
2.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()方法使用負下標時,將從陣列的末尾訪問元素,
const lastItem = fruits.at(-1);
lastItem; // => 'grape'
下面是更詳細的array.at()方法示例:
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'
3. 總結
JS 中的方括號語法是通過索引訪問項的常用且好的方法,只需將索引運算式放入方括號array[index]中,并獲取該索引處的陣列項,
然而,使用常規訪問器從末尾訪問項并不方便,因為它不接受負索引,因此,例如,要訪問陣列的最后一個元素,必須使用一個變通運算式
const lastItem = array[array.length - 1];
幸運的是,新的陣列方法array.at(index)允許我們以常規訪問器的方式通過索引訪問陣列元素,而且,array.at(index)接受負索引,在這種情況下,該方法從末尾取元素:
const lastItem = array.at(-1);
只需將array.prototype.at polyfill引入到我們的應用程式中,就可以使用 array.at() 方法了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/258079.html
標籤:其他
下一篇:同構與異構
