Home  >  Article  >  Web Front-end  >  How do I retrieve array elements by their indices in JavaScript?

How do I retrieve array elements by their indices in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 07:17:02761browse

How do I retrieve array elements by their indices in JavaScript?

Retrieving Array Elements at Specific Indices in JavaScript: A Comprehensive Guide

Question:

How can we obtain the value stored at a particular index within an array in JavaScript? We have an array with a value at index 1 but require a method to retrieve it effortlessly.

Answer:

Accessing array elements by index is a fundamental operation in JavaScript. There are two primary methods for doing so:

1. Bracket Notation:

The bracket notation provides a straightforward way to access array elements. It involves specifying the target index within square brackets appended to the array name. For instance:

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

2. .at() Method:

Available in modern browsers and JavaScript engines, the .at() method offers a more flexible approach. It can both access elements from the start and end of the array using positive and negative indices, respectively. Here's an example:

<code class="javascript">var valueAtIndex1 = myValues.at(1);</code>

On positive indices, both methods behave identically. Bracket notation is more commonly used, while .at() allows for accessing elements from the end using negative indices (-1 refers to the last element, -2 to the second last element, and so on).

Additional Notes:

  • The index of the first element in an array is 0.
  • When using negative indices with the .at() method, indices below -array.length will overflow and provide values from the positive end of the array.

For further details and examples, refer to the MDN documentation on [Array.prototype.at()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at).

The above is the detailed content of How do I retrieve array elements by their indices in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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