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