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];
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
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!