Home > Mobile >  What is the use of ".at()" in JavaScript?And does it work in normal javascript (browser ja
What is the use of ".at()" in JavaScript?And does it work in normal javascript (browser ja

Time:10-17

 array.at() 

Or is it for node.js or javascript!

CodePudding user response:

This is a pretty new proposal. The idea behind it is:

A TC39 proposal to add an .at() method to all the basic indexable classes (Array, String, TypedArray)

For many years, programmers have asked for the ability to do "negative indexing" of JS Arrays, like you can do with Python. That is, asking for the ability to write arr[-1] instead of arr[arr.length-1], where negative numbers count backwards from the last element.

Unfortunately, JS's language design makes this impossible. The [] syntax is not specific to Arrays and Strings; it applies to all objects. Referring to a value by index, like arr[1], actually just refers to the property of the object with the key "1", which is something that any object can have. So arr[-1] already "works" in today's code, but it returns the value of the "-1" property of the object, rather than returning an index counting back from the end.

This proposal instead adopts a more common approach, and suggests adding a .at() method to Array, String, and TypedArray, which takes an integer value and returns the item at that index, with the negative-number semantics as described above.

So somethingIndexed.at(n) is essentially the same as somethingIndexed[n] - except that n can be negative.

.at(-1) is equivalent to somethingIndexed[somethingIndexed.length - 1].

.at(-2) is equivalent to somethingIndexed[somethingIndexed.length - 2].

And so on.

const arr = ['foo', 'bar', 'baz'];
console.log(arr.at(-1) === arr[arr.length - 1]);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

But it's quite a new proposal. Eventually, it'll be integreated into all modern environments (including Node and browsers), but since it's so new (and not even stage 4 yet), you should not count on it being supported yet. Only use it in production code if you include a polyfill.

  • Related