How do I insert an element at a specific index at a JS array?
Requirements: Inserts an element into an existing array at a specific index. 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)
//Stitching function (index position, number of elements to be deleted, elements
) Array.splice (2, 0, "three");
array;//Now arrays are this way ["one", "two", "three", "four"]
If you are not disgusted with expanding native JavaScript, you can add this method to the array prototype (prototype):
Array.prototype.insert = function (index, item) {
This.splice (index, 0, item);
At this point, you can call this:
var nums = ["One", "two", "four"];
Nums.insert (2, ' three '); Note the array index, [0,1,2 ...]
Array//["One", "two", "three", "four"]