您的位置:首页 > Web前端 > JavaScript

JS数组将要增加的新方法:array.at(index)

2021-01-27 22:43 1031 查看

JS数组将要增加的新方法:array.at(index)

疯狂的技术宅 前端先锋

// 每日前端夜话 第471篇
// 正文共:1200 字
// 预计阅读时间:7 分钟

除了普通对象之外,数组是 JavaScript 中使用最广泛的数据结构。数组上最常使用的操作是按索引访问元素。

本文介绍新的数组方法 array.at(index)。

新方法最主要好处是可以用负索引从数组末尾访问元素,而平时使用的方括号语法 array[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阶段) (https://github.com/tc39/proposal-relative-indexing-method)将 at() 方法引入了数组(以及类型化数组和字符串),并解决了方括号的许多限制。

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 (https://github.com/es-shims/Array.prototype.at) polyfill 包含到你的应用程序中,就可以使用 array.at() 了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: