Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Array.at(index) instead of Array[index] in JavaScript

I have a question about Array.at() method that was introduced Array.prototype.at() - MDN. It seems more useful than squared brackets annotation arr[i] since there is an option to specify index starting from the end of an array, for example: arr.at(-1) which would return the last member of arr array. Also, it seems more appropriate for method chaining. Are there any downsides to switching to it?

like image 608
Ilija Ivic Avatar asked Dec 23 '21 02:12

Ilija Ivic


People also ask

How can you replace an element at a specific index in an array?

To replace an element in an array: Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.

Can you use indexOf for an array?

Introduction to the JavaScript array indexOf() methodTo find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

What is array index in JavaScript?

JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 . JavaScript array-copy operations create shallow copies.

Can I use array prototype at ()?

Array.prototype.at()The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.


Video Answer


1 Answers

A couple of disadvantages to it are:

  • It's a very new method. Older browsers will not be able to understand your code if you use it, unless you include a polyfill - so make sure you include one..
  • On a completely different track, since it's such a new method, I wouldn't be surprised if a substantial number of developers haven't heard about it - using .at may confuse some of them (and cause them to have to look it up). Not that this means that you shouldn't use it, but it's something to keep in mind.
like image 190
CertainPerformance Avatar answered Sep 30 '22 02:09

CertainPerformance