如何在JavaScript的特定数组索引处获取值?


93

我有一个数组,只是想在索引1处获取元素。

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

如何在JavaScript中数组的第一个索引处获取值?

Answers:



36

JavaScript中数组索引的第一项从零开始,因此请尝试以下操作:

var firstArrayItem = myValues[0]

当然,如果您实际上希望数组中的第二项位于索引1,则为myValues[1]

有关更多信息,请参见访问数组元素




0

shift可以在要获取index=0数组的第一个元素()并与其他数组方法链接的地方使用。

例:

const comps = [{}, {}, {}]
const specComp = comps
                  .map(fn1)
                  .filter(fn2)
                  .shift()

记住要shift对数组进行突变,这与通过索引器进行访问非常不同。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.