How to get value at a specific index of array In JavaScript?

I have an array and simply want to get the element at index 1.

var myValues = new Array();
var valueAtIndex1 = myValues.getValue(1); // (something like this)

How can I get the value at the 1st index of my array in JavaScript?



Just use indexer

var valueAtIndex1 = myValues[1];

Array indexes in JavaScript start at zero for the first item, so try this:

var firstArrayItem = myValues[0]

Of course, if you actually want the second item in the array at index 1, then it's myValues[1].

See Accessing array elements for more info.


You can just use []:

var valueAtIndex1 = myValues[1];

You can use [];

var indexValue = Index[1];

shift can be used in places where you want to get the first element (index=0) of an array and chain with other array methods.


const comps = [{}, {}, {}]
const specComp = comps

Remember shift mutates the array, which is very different from accessing via an indexer.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.