Many array-related tasks sound simple, but they are not always the case, and developers often don't use it. Recently I encountered a requirement: 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) // 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"]