How to insert an element at a specified position at a JS array specific index?
Requirements: Insert an element at 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)// splice function (index position, number of elements to be deleted, element) array.splice(2, 0, "three"); // array; // Now the array looks like this ["one", "two", "three", "four"]
If you are not disgusted with extending native JavaScript, you can add this method to the Array prototype:
Array.prototype.insert = function (index, item) {this.splice(index, 0, item);};At this time, you can call it like this:
var nums = ["one", "two", "four"];nums.insert(2, 'three'); // Note the array index, [0,1,2..]array // ["one", "two", "three", "four"]