Home > Web Front-end > JS Tutorial > Using Array.at() over Array[index]

Using Array.at() over Array[index]

Mary-Kate Olsen
Release: 2025-01-19 14:30:15
Original
613 people have browsed it

Using Array.at() over Array[index]

This article will explore why Array.prototype.at() is more ideal than Array[index] when accessing array elements.

Motivation

In the past, when accessing array elements, I used to use Array[index], such as Array[1]. This is what I'm familiar with and how I learned to get array elements.

However, a colleague recently asked in a code review: "Why not use Array.prototype.at() instead of using the index directly?"

My code is:

<code class="language-javascript">const element = arr[1];</code>
Copy after login
Copy after login

He suggested changing to:

<code class="language-javascript">const element = arr.at(1);</code>
Copy after login

This approach stands out to me because it looks very simple and intuitive.

How to use Array.prototype.at()

Array.prototype.at() accepts an integer as argument and returns the corresponding element in the array.

For example, for an array:

<code class="language-javascript">const arr = ["One", "Two", "Three"];</code>
Copy after login

Call:

<code class="language-javascript">arr.at(0); // 返回 "One"</code>
Copy after login

This is equivalent to the square bracket notation array[0]. You may be wondering, what's the difference? Next we’ll dive into the advantages of using this approach.

Why is Array[index] not ideal?

Let’s look at some scenarios where Array.prototype.at() should be used instead of Array[index].

Get the last element of the array

Suppose there is an array of strings:

<code class="language-javascript">const sports = ["basketball", "baseball", "football"];</code>
Copy after login

To get the last element "football" of the array, you can write:

<code class="language-javascript">const lastElement = sports[sports.length - 1];</code>
Copy after login

This is the correct approach; however, it can be written more concisely using the Array.prototype.at() method:

<code class="language-javascript">const lastElement = sports.at(-1);</code>
Copy after login

Is it easier to read?

Type inference

In TypeScript, square bracket notation does not include undefined in type inference.

<code class="language-typescript">const arr: string[] = [];
const element = arr[0];
console.log(element); // undefined</code>
Copy after login
The type of

element is inferred as string, not string | undefined.

We expect TypeScript to give compilation errors when writing this code.

Typically, we want to ensure that the array element being accessed exists.

<code class="language-typescript">const arr: string[] = [];
const element = arr[0];
if (typeof element === 'string') console.log(element);</code>
Copy after login

The weird thing is that we are checking the element type that TypeScript infers as string.

You might think of using type assertions:

<code class="language-typescript">const element: string | undefined = arr[0];</code>
Copy after login

However, this is not ideal as we should not take it upon ourselves to write perfect code.

To solve this problem, we can take two approaches:

  1. Write type protection functions
  2. Use the noUncheckedIndexedAccess compiler option

Both methods work well, but if you use Array.prototype.at() you don't need to do both.

<code class="language-typescript">const arr: string[] = [];
const element = arr.at(0); // string | undefined
console.log(element);</code>
Copy after login

If you try to insert element into another value of type string you will get a compile error:

<code class="language-javascript">const element = arr[1];</code>
Copy after login
Copy after login

Conclusion

Use Array.prototype.at() to write cleaner code and avoid adding extra functions and configuration.

Array.prototype.at() Explanation on Mozilla Developer Network: Link (please replace with actual link)

The above is the detailed content of Using Array.at() over Array[index]. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template