Home > Web Front-end > JS Tutorial > body text

How do you access values at specific indices in a JavaScript array?

Mary-Kate Olsen
Release: 2024-10-25 21:28:02
Original
396 people have browsed it

How do you access values at specific indices in a JavaScript array?

Accessing Values at Specific Array Indices in JavaScript

To access the value at a specific index in an array in JavaScript, you can utilize the following methods:

Bracket Notation

The most common approach is to use the bracket notation accessor, where you enclose the desired index within square brackets. For instance, if you have an array myValues, you can retrieve the element at index 1 as follows:

const valueAtIndex1 = myValues[1];
Copy after login

Array.prototype.at() Method

On modern browsers and JavaScript engines, you can also use the .at() method on arrays. This method provides similar functionality to the bracket notation but offers extended capabilities, such as accessing elements from the end of the array using negative indices. For example:

const valueAtIndex1 = myValues.at(1); // Positive index

const lastValue = myValues.at(-1); // Last element
Copy after login

Choosing the Right Method

Both the bracket notation and .at() method effectively retrieve array elements at specific indices. The bracket notation is widely supported and generally preferred. However, .at() offers additional features that can be useful in specific cases, such as handling negative indices.

It's important to note that trying to access an index outside the array's bounds will result in undefined being returned.

The above is the detailed content of How do you access values at specific indices in a JavaScript array?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!