This content originally appeared on David Walsh Blog and was authored by David Walsh
Working with arrays is an essential skill in any programming language, especially JavaScript, as we continue to rely on external data APIs. JavaScript has added methods like find
and `findIndex
recently, but one syntax I love from languages like Python is retrieving values by negative indexes.
When you want to get the value of the last item in an array, you end up with an archaic expression:
const arr = ["zero", "one", "two", "three"]; const last = arr[arr.length - 1];
You could use pop
but that modifies the array. 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 shorthand syntax!
The post Array.prototype.at appeared first on David Walsh Blog.
This content originally appeared on David Walsh Blog and was authored by David Walsh
David Walsh | Sciencx (2021-11-08T01:50:20+00:00) Array.prototype.at. Retrieved from https://www.scien.cx/2021/11/08/array-prototype-at/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.