2

Using the new array.at() method

 3 years ago
source link: http://www.js-craft.io/blog/using-the-new-array-at-method/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Using the new array.at() method

There is a new array method on the block. It's array.at() and the main difference vs the normal square brackets access syntax is the support for the negative indexes.

Let's consider the following array:

const legumes = [
    "beans", 
    "peanuts", 
    "clover",
    "lentils"
]

At a first glace [] and at() will do the same thing:

legumes[0] // "beans"
legumes.at(0) // "beans"

But while legumes[-1] will end up in returning undefined the legumes.at(-1) will return "lentils".

legumes[-1] // undefined
legumes.at(-1) // "lentils"

With the classic square brackets syntax, we will need to use a trick like the following to access the last element in the array:

legumes[legumes.length - 1] // lentils

The negative indexes in the at() method will give us a more natural way to access elements at the end of the array:

legumes.at(-2) // "clover"
legumes.at(-3) // "peanuts"

Keep in mind that for the moment Safari does not yet support negative indexes.

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.

Newsletter subscribe:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK