Use unshift
.
(使用unshift
。)
It's like push
, except it adds elements to the beginning of the array instead of the end. (就像push
一样,除了将元素添加到数组的开头而不是结尾。)
A simple diagram...
(一个简单的图...)
unshift -> array <- push
shift <- array -> pop
and chart:
(和图表:)
add remove start end
push X X
pop X X
unshift X X
shift X X
Check out the MDN Array documentation .
(查看MDN阵列文档 。)
Virtually every language that has the ability to push/pop elements from an array will also have the ability to unshift/shift (sometimes called push_front
/ pop_front
) elements, you should never have to implement these yourself. (实际上,每种能够从数组中推入/弹出元素的语言都将具有取消/移入(有时称为push_front
/ pop_front
)元素的能力,您永远不必自己实现这些元素。)
As pointed out in the comments, if you want to avoid mutating your original array, you can use concat
, which concatenates two or more arrays together.
(如注释中所指出的那样,如果要避免更改原始数组,可以使用concat
,它将两个或多个数组连接在一起。)
You can use this to functionally push a single element onto the front or back of an existing array; (您可以使用它在功能上将单个元素推到现有数组的前面或后面;)
to do so, you need to turn the new element into a single element array: (为此,您需要将新元素转换为单个元素数组:)
const array = [ 3, 2, 1 ]
const newFirstElement = 4
const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]
concat
can also append items.
(concat
也可以附加项目。)
The arguments to concat
can be of any type; (concat
的参数可以是任何类型。)
they are implicitly wrapped in a single-element array, if they are not already an array: (如果它们还不是数组,则将它们隐式包装在单元素数组中:)
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 ]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…