使用unshift
. 就像push
,除了它将元素添加到数组的开头而不是结尾。
unshift
/ push
- 在数组的开头/结尾添加一个元素
shift
/ pop
- 删除并返回数组的第一个/最后一个元素
一个简单的图...
unshift -> array <- push
shift <- array -> pop
和图表:
add remove start end
push X X
pop X X
unshift X X
shift X X
查看MDN 数组文档。实际上,每一种能够从数组中推送/弹出元素的语言也都能够取消/移动(有时称为push_front
/ pop_front
)元素,您永远不必自己实现这些。
正如评论中指出的那样,如果您想避免改变原始数组,可以使用concat
,它将两个或多个数组连接在一起。您可以使用它在功能上将单个元素推送到现有数组的前面或后面;为此,您需要将新元素转换为单个元素数组:
const array = [3, 2, 1]
const newFirstElement = 4
const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]
console.log(newArray);
concat
也可以追加项目。的参数concat
可以是任何类型;如果它们还不是数组,它们将被隐式包装在一个单元素数组中:
const array = [3, 2, 1]
const newLastElement = 0
// Both of these lines are equivalent:
const newArray1 = array.concat(newLastElement) // [ 3, 2, 1, 0 ]
const newArray2 = array.concat([newLastElement]) // [ 3, 2, 1, 0 ]
console.log(newArray1);
console.log(newArray2);