附加单个项目 (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.
请记住,如前所述,此方法不会突变原始数组,但会返回一个新数组。