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 =
splice()
function is the only native array function that lets you add elements to the specific place of an arrayI will get a one array that you entered in your question to describe
splice(position, numberOfItemsToRemove, item)
position
= What is the position that you want to add new itemnumberOfItemsToRemove
= This indicate how many number of items will deleted. That's
mean delete will start according to the position that new item add.Ex = if you want to add 1 position to 123 result will be like this ([4,123,0,5,9,6,2,5]) but if you give
numberOfItemsToRemove
to 1 it will remove first element after the 123 if you give 2 then its delete two element after 123.
item
= the new item that you addfunction my_func(){
var suits = [4,0,5,9,6,2,5]
suits.splice(1 , 0 , 123);
document.getElementById('demo').innerHTML = suits;
}
<button id="btn01" onclick="my_func()">Check</button>
<p id="demo"></p>
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]
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"]