关于javascript:你会喜欢的新数组方法arrayatindex

4次阅读

共计 2320 个字符,预计需要花费 6 分钟才能阅读完成。

作者:dmitripavlutin
译者:前端小智
起源:dmitripavlutin

最近开源了一个 Vue 组件,还不够欠缺,欢送大家来一起欠缺它,也心愿大家能给个 star 反对一下,谢谢各位了。

github 地址:https://github.com/qq44924588…

除了一般对象之外,数组是 JavaScript 中宽泛应用的数据结构,而数组中罕用操作是按索引拜访元素。在本文中,咱们介绍新的数组办法array.at(index)

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

示例地址:https://codesandbox.io/s/arra…

如果 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() 办法了。

完~ 我是小智,我要去刷碗了,咱们下期见~


代码部署后可能存在的 BUG 没法实时晓得,预先为了解决这些 BUG,花了大量的工夫进行 log 调试,这边顺便给大家举荐一个好用的 BUG 监控工具 Fundebug。

原文:https://dmitripavlutin.com/ja…

交换

文章每周继续更新,能够微信搜寻「大迁世界」第一工夫浏览和催更(比博客早一到两篇哟),本文 GitHub https://github.com/qq449245884/xiaozhi 曾经收录,整顿了很多我的文档,欢送 Star 和欠缺,大家面试能够参照考点温习,另外关注公众号,后盾回复 福利,即可看到福利,你懂的。

正文完
 0