Suppose you have an array, like this:
假设您有一个数组,如下所示:
const colors = ['red', 'yellow', 'green', 'blue']
How can you get the last item in the array?
如何获得数组中的最后一项?
In this case the array has 4 items.
在这种情况下,数组有4个项目。
You know you can get the first item using colors[0]
, the second using colors[1]
and so on.
您知道可以使用colors[0]
来获得第一项,使用colors[1]
来获得第二项,依此类推。
To get the last item without knowing beforehand how many items it contains, you can use the length
property to determine it, and since the array count starts at 0, you can pick the last item by referencing the <array>.length - 1
item.
要获取最后一个项目而不事先知道它包含多少个项目,可以使用length
属性来确定它,并且由于数组计数从0开始,因此您可以通过引用<array>.length - 1
项目来选择最后一个项目。 。
In this case:
在这种情况下:
const lastItem = colors[colors.length - 1]
翻译自: https://flaviocopes.com/how-to-get-last-item-array-javascript/