如何在JavaScript中的数组开头添加项目

Say you want to add an item at the beginning of an array.

假设您要在数组的开头添加一个项目。

To perform this operation you will use the splice() method of an array.

要执行此操作,您将使用数组的splice()方法。

splice() takes 3 or more arguments. The first is the start index: the place where we’ll start making the changes. The second is the delete count parameter. We’re adding to the array, so the delete count is 0 in all our examples. After this, you can add one or many items to add to the array.

splice()接受3个或更多参数。 第一个是开始索引:我们将开始进行更改的地方。 第二个是删除计数参数。 我们将添加到数组,因此在所有示例中,删除计数均为0。 之后,您可以添加一个或多个项目以添加到阵列。

To add at the first position, use 0 as the first argument:

要在第一个位置添加,请使用0作为第一个参数:

const colors = ['yellow', 'red']

colors.splice(0, 0, 'blue')

//colors === ['blue', 'yellow', 'red']

翻译自: https://flaviocopes.com/how-to-add-item-beginning-array-js/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值