你會喜歡的新數(shù)組方法:array.at(index)
本文已經(jīng)過 dmitripavlutin 授權翻譯!
除了普通對象之外,數(shù)組是 JavaScript 中廣泛使用的數(shù)據(jù)結構,而數(shù)組中常用操作是按索引訪問元素。在本文中,我們介紹新的數(shù)組方法array.at(index)。
1.方括號語法的局限性
通過索引訪問數(shù)組元素一般使用方括號array[index]:
- const fruits = ['orange', 'apple', 'banana', 'grape'];
- const item = fruits[1];
- item; // => 'apple'
表達式array[index]求值為位于index的數(shù)組項,這種方式也叫屬性訪問器。
在大多數(shù)情況下,方括號語法是通過正索引(>= 0)訪問項的好方法,它的語法簡單且可讀。
但有時我們希望從末尾訪問元素,而不是從開始訪問元素。例如,訪問數(shù)組的最后一個元素:
- const fruits = ['orange', 'apple', 'banana', 'grape'];
- const lastItem = fruits[fruits.length - 1];
- lastItem; // => 'grape'
fruits[fruits.length - 1]是訪問數(shù)組最后一個元素的方式,其中fruits.length - 1是最后一個元素的索引。
問題在于方括號訪問器不允許直接從數(shù)組末尾訪問項,也不接受負下標。
幸運的是,一個新的提議(截至2021年1月的第3階段)將at()方法引入了數(shù)組(以及類型化的數(shù)組和字符串),并解決了方括號訪問器的諸多限制。
2.array.at() 方法
簡單來說,array.at(index)訪問index參數(shù)處的元素。
如果index參數(shù)是一個正整數(shù)>= 0,該方法返回該索引處的項目。
- const fruits = ['orange', 'apple', 'banana', 'grape'];
- const item = fruits.at(1);
- item; // => 'apple'
如果index參數(shù)大于或等于數(shù)組長度,則與常規(guī)訪問器一樣,該方法返回undefined:
- const fruits = ['orange', 'apple', 'banana', 'grape'];
- const item = fruits.at(999);
- item; // => undefined
真正神奇的是,當你對array.at()方法使用負下標時,將從數(shù)組的末尾訪問元素。
- 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
示例地址:https://codesandbox.io/s/array-at-method-2xr74?file=/src/index.js
如果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]中,并獲取該索引處的數(shù)組項。
然而,使用常規(guī)訪問器從末尾訪問項并不方便,因為它不接受負索引。因此,例如,要訪問數(shù)組的最后一個元素,必須使用一個變通表達式
- const lastItem = array[array.length - 1];
幸運的是,新的數(shù)組方法array.at(index)允許我們以常規(guī)訪問器的方式通過索引訪問數(shù)組元素。而且,array.at(index)接受負索引,在這種情況下,該方法從末尾取元素:
- const lastItem = array.at(-1);
只需將array.prototype.at polyfill引入到我們的應用程序中,就可以使用 array.at() 方法了。
完~ 我是小智,我要去刷碗了,我們下期見~
作者:dmitripavlutin 譯者:前端小智 來源:dmitripavlutin
本文轉(zhuǎn)載自微信公眾號「大遷世界」,作者大遷世界。轉(zhuǎn)載本文請聯(lián)系大遷世界公眾號。