The technique of inserting an element at a specified location at a specific index of a JS array
- 2020-03-30 03:46:36
- OfStack
How do I insert an element at a specific index in a JS array?
Requirement: to insert an element into a specific index of an existing array. It sounds easy and common, but it takes a little time to study it.
//The original array
var array = ["one", "two", "four"];
// splice(position, numberOfItemsToRemove, item)
//Splicing function (index position, number of elements to delete, element)
array.splice(2, 0, "three"); //
array; // Now the array looks like this ["one", "two", "three", "four"]
If you're comfortable with extending native JavaScript, you can add this method to an Array prototype:
Array.prototype.insert = function (index, item) {
this.splice(index, 0, item);
};
At this point, you can call:
var nums = ["one", "two", "four"];
nums.insert(2, 'three'); //Note the array index, [0,1,2..]
array // ["one", "two", "three", "four"]