web123456

Insert element at specified location in JS array

Original link:Array: Insert an Item at a Specific Index with JavaScript
Original date: July 24, 2014
Translation date: July 26, 2014
Translator:Iron anchor

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)
 //Sticking function (index position, number of elements to be deleted, element)
 (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:
 = function (index, item) {
  (index, 0, item);
};

At this time, you can call it like this:
var nums = ["one", "two", "four"];
 (2, 'three'); // Pay attention to array index, [0,1,2..]
 array // ["one", "two", "three", "four"]

I've made some other modifications to the array, maybe you've seen it:
  • Remove an Item From an Array: Remove elements from array
  • Clone Arrays: Array cloning
  • Empty Arrays: Empty array
  • Sort Arrays: Array sorting
Arrays is very useful - it is still quite cumbersome to handle certain tasks in JavaScript... You have to write more code than you actually need. For more convenience, please bookmark this article, or save these clips to your toolbox!