如何在JavaScript中将项目追加到数组

附加单个项目 (Append a single item)

To append a single item to an array, use the push() method provided by the Array object:

要将单个项目附加到数组,请使用Array对象提供的push()方法:

const fruits = ['banana', 'pear', 'apple']
fruits.push('mango')

push() mutates the original array.

push()更改原始数组。

To create a new array instead, use the concat() Array method:

要创建一个新数组,请使用concat() Array方法:

const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango')

Notice that concat() does not actually add an item to the array, but creates a new array, which you can assign to another variable, or reassign to the original array (declaring it as let, as you cannot reassign a const):

请注意, concat()实际上并未向该数组添加项目,而是创建了一个新数组,您可以将其分配给另一个变量,或重新分配给原始数组(将其声明为let ,因为您无法重新分配const ):

let fruits = ['banana', 'pear', 'apple']
fruits = fruits.concat('mango')

追加多个项目 (Append multiple items)

To append a multiple item to an array, you can use push() by calling it with multiple arguments:

要将多个项目附加到数组,可以使用带有多个参数的push()来使用它:

const fruits = ['banana', 'pear', 'apple']
fruits.push('mango', 'melon', 'avocado')

You can also use the concat() method you saw before, passing a list of items separated by a comma:

您还可以使用之前看到的concat()方法,传递以逗号分隔的项目列表:

const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat('mango', 'melon', 'avocado')

or an array:

或数组:

const fruits = ['banana', 'pear', 'apple']
const allfruits = fruits.concat(['mango', 'melon', 'avocado'])

Remember that as described previously this method does not mutate the original array, but it returns a new array.

请记住,如前所述,此方法不会突变原始数组,但会返回一个新数组。

翻译自: https://flaviocopes.com/how-to-append-item-to-array/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值