如何在 JavaScript 中获取数组特定索引处的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8238456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get value at a specific index of array In JavaScript?
提问by junaidp
I have an array and simply want to get the element at index 1.
我有一个数组,只想获取索引 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?
如何在 JavaScript 中获取数组的第一个索引处的值?
回答by Abdul Munim
Just use indexer
只需使用 indexer
var valueAtIndex1 = myValues[1];
回答by Chris Fulstow
Array indexes in JavaScript start at zero for the first item, so try this:
JavaScript 中的数组索引从第一项的零开始,所以试试这个:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1]
.
当然,如果您确实想要数组中索引 1 处的第二项,那么它是myValues[1]
.
See Accessing array elementsfor more info.
有关更多信息,请参阅访问数组元素。
回答by Petar Ivanov
You can just use []
:
你可以只使用[]
:
var valueAtIndex1 = myValues[1];
回答by Zain Jamil
You can use [];
您可以使用 [];
var indexValue = Index[1];
回答by Subrat
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.
shift
可用于您想要获取index=0
数组的第一个元素 ( ) 并与其他数组方法链接的地方。
example:
例子:
const comps = [{}, {}, {}]
const specComp = comps
.map(fn1)
.filter(fn2)
.shift()
Remember shift
mutates the array, which is very different from accessing via an indexer.
记住shift
改变数组,这与通过索引器访问非常不同。