通过索引访问数组元素一般使用方括号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()方法引入了数组(以及类型化的数组和字符串),并解决了方括号访问器的诸多限制。
简单来说,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'
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()
方法了。