简体   繁体   English

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

[英]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.我有一个数组,只想获取索引 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 中的数组的第一个索引处获取值?

只需使用indexer

var valueAtIndex1 = myValues[1];

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 elements for more info.有关更多信息,请参阅访问数组元素

你可以只使用[]

var valueAtIndex1 = myValues[1];

indexer ( array[index] ) is the most frequent use.索引器( array[index] ) 是最常用的。 An alternative is at array method:另一种方法at数组方法:

const cart = ['apple', 'banana', 'pear'];
cart.at(0) // 'apple'
cart.at(2) // 'pear'

If you come from another programming language, maybe it looks more familiar.如果您来自另一种编程语言,也许它看起来更熟悉。

您可以使用[];

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. 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数组,这与通过索引器访问非常不同。

Update 2022 2022 年更新

With ES2022 you can use Array.prototype.at() :使用 ES2022,您可以使用Array.prototype.at()

const myValues = [1, 2, 3]
myValues.at(1) // 2

at() also supports negative index, which returns an element from the end of the array: at()还支持负索引,它从数组末尾返回一个元素

const myValues = [1, 2, 3]
myValues.at(-1) // 3
myValues.at(-2) // 2

Read more: MDN , JavascriptTutorial , Specifications阅读更多: MDNJavascriptTutorial规范

As you specifically want to get the element at index 1. You can also achieve this by using Array destructuring from ES6.因为您特别想获取索引 1 处的元素。您也可以通过使用 ES6 中的 Array 解构来实现此目的。

const arr = [1, 2, 3, 4];
const [zeroIndex, firstIndex, ...remaining] = arr;
console.log(firstIndex); // 2

Or, As per ES2022.或者,根据 ES2022。 You can also use Array.at()您也可以使用Array.at()

const arr = [1, 2, 3, 4];
console.log(arr.at(1)); // 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM