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/