How to push to an array in a particular position?

2019-02-06 01:40发布

问题:

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]

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

Thanks!

回答1:

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]


回答2:

To push any item at specific index in array use following syntax

// The original array
var array = ["one", "two", "four"];
// splice(position, numberOfItemsToRemove, item)
array.splice(2, 0, "three");

console.log(array);  // ["one", "two", "three", "four"]