Sunday 22 October 2017

javascript - How to push to an array in a particular position?

itemprop="text">


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!



Answer




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]


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...