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