Date:

Share:

Array.prototype.at

Related Articles

Working with arrays is an essential skill in any programming language, especially JavaScript, as we continue to rely on external data APIs. JavaScript added methods like find And`findIndex Recently, but one syntax I like from languages ​​like Python is retrieving values ​​by negative indexes.

When you want to get the value of the last item in the array, you get an archaic expression:

const arr = ["zero", "one", "two", "three"];
const last = arr[arr.length - 1];

You can use pop But that changes the lineup. Instead you can use at And an index, even a negative index, to retrieve values:

const arr = ["zero", "one", "two", "three"];
arr.at(-1); // "three"
arr.at(-2); // "two"
arr.at(0); // "zero"

at Is a very little known function but useful, if only for the syntax of the abbreviation!

  • How to create a Twitter card
  • Fetch API

    Fetch API

    One of the best kept secrets about AJAX on the web is that the basic API for it, XMLHttpRequest, Not really created for what we used. We’ve done well to create elegant APIs around XHR but we know we can do better. Our effort to …


Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles