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

How to Access Elements at Specific Indices in JavaScript Arrays?

DDD
Release: 2024-10-27 14:49:01
Original
753 people have browsed it

How to Access Elements at Specific Indices in JavaScript Arrays?

Obtaining Values at Specific Array Indices in JavaScript

In JavaScript, you can efficiently retrieve elements at specific indices within arrays. Here's how:

Using Bracket Notation Accessor

The bracket notation accessor allows you to access array elements using the index as the key within brackets. For instance:

<code class="javascript">var myValues = new Array();
var valueAtIndex1 = myValues[1];</code>
Copy after login

Using the .at() Method (ECMAScript 2015)

Newer JavaScript engines support the .at() method on arrays, which provides an alternative way to access elements at specific indices. It works similarly to the bracket notation, but allows for negative indices:

<code class="javascript">var valueAtIndex1 = myValues.at(1); // Same as myValues[1]</code>
Copy after login

Positive Indices

For positive indices, both the bracket notation and .at() methods act identically.

Negative Indices

However, the .at() method adds functionality for negative indices. Passing -1 retrieves the last element, -2 gets the second-to-last element, and so on:

<code class="javascript">var lastElement = myValues.at(-1);</code>
Copy after login

MDN Documentation

Refer to the MDN documentation for more details on accessing array elements in JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at

The above is the detailed content of How to Access Elements at Specific Indices in JavaScript Arrays?. 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
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!