This article describes how to insert an element at a specified position in a specific index of the JS array? Insert an element to a specific index of an existing array. For more information, see how to insert an element at a specified position in a specific index of the JS array?
Requirement: insert an element to a specific index of the existing array. It sounds easy and common, but it takes some time to study it.
// Original array var array = ["one", "two", "four"]; // splice (position, numberOfItemsToRemove, item) // concatenation function (index location, number of elements to be deleted, element) array. splice (2, 0, "three"); // array; // The current array looks like this ["one", "two", "three", "four"]
If you are not disgusted with native JavaScript extension, you can add this method to the Array prototype:
Array. prototype. insert = function (index, item) {this. splice (index, 0, item );};
In this case, you can call:
Var nums = ["one", "two", "four"]; nums. insert (2, 'three '); // note the array index, [, 2 ..] array // ["one", "two", "three", "four"]