js insert in array 1

js insert in array

var colors=["red","blue"];
var index=1;

//insert "white" at index 1
colors.splice(index, 0, "white");   //colors =  ["red", "white", "blue"]

Here is what the above code is Doing:
1. We create an array called colors with two elements, “red” and “blue”.
2. We create a variable called index and set it to 1.
3. We use the splice() method to insert “white” at index 1.
4. We print out the new array.

Similar Posts