如何在JavaScript中获取数组的最后一个元素?

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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值