Home >Web Front-end >JS Tutorial >How to Insert Elements into a JavaScript Array at a Specific Index?
Array Insertion: Inserting Items at Specific Indices
Inserting items at precise indices within an array is a common programming task. In JavaScript, there isn't an explicit "insert" method for arrays. However, there's a versatile solution utilizing the native array function splice.
The splice function allows modifying an array by inserting, deleting, or replacing elements. To insert an item at a particular index, use the following syntax:
arr.splice(index, 0, item);
Here, the first parameter index represents the position where the new item should be inserted. Passing 0 as the second parameter indicates no deletion, effectively inserting the new item item into the array.
For instance, let's create an array:
var arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge";
To insert the name "Lene" at index 2, we can use the following code:
arr.splice(2, 0, "Lene");
This modification will result in the array:
["Jani", "Hege", "Lene", "Stale", "Kai Jim", "Borge"]
By utilizing the splice function, you can conveniently insert items into arrays at specific locations without the need for complex array manipulation techniques.
The above is the detailed content of How to Insert Elements into a JavaScript Array at a Specific Index?. For more information, please follow other related articles on the PHP Chinese website!