如何推送到特定位置的数组?

2022-01-24 00:00:00 arrays javascript coffeescript

我正在尝试有效地编写一个语句,该语句将推送到数组的位置 1,并将该位置中的任何内容或之后的内容推送回一个位置.

I'm trying to efficiently write a statement that pushes to position 1 of an array, and pushes whatever is in that position, or after it back a spot.

array = [4,5,9,6,2,5]

#push 0 to position 1

array = [4,0,5,9,6,2,5]

#push 123 to position 1

array = [4,123,0,5,9,6,2,5]

写这个的最好方法是什么?(可以接受javascript或coffeescript)

What is the best way to write this? (javascript or coffeescript acceptable)

谢谢!

推荐答案

array = [4,5,9,6,2,5]

#push 0 to position 1
array.splice(1,0,0)

array = [4,0,5,9,6,2,5]

#push 123 to position 1
array.splice(1,0,123)

array = [4,123,0,5,9,6,2,5]

相关文章