Array.prototype.at

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!

  • 5 ways to interact between CSS and JavaScript that you may not have known about
  • 39 shirts - leaving Mozilla

    39 shirts – leaving Mozilla

    Just in 2001 I graduated from high school in a small town and went to college in a small town. I found myself in the weird computer lab where the non-standard computers included two browsers: Internet Explorer and Mozilla. This was the lab where I fell …

  • MooTools Equal Heights plugin: Equalizer

    MooTools Equal Heights plugin: Equalizer

    Maintaining equal heights between elements in the same container can be very important for a beautiful page. Unfortunately, sometimes you can not keep columns at the same height with CSS – you need some help from your JavaScript authors. Well … now you …

  • Scroll “Go up” link using Dojo

    Scroll to the “Go to Top” link using Dojo

    One of the most popular code snippets posted on my blog was the “Go Up” scrolling link section. The premise of the passage is simple: once the user scrolls an element (usually a BODY element) beyond a given threshold, “for …


Source
spot_img

LEAVE A REPLY

Please enter your comment!
Please enter your name here