Home >Web Front-end >JS Tutorial >How to Insert an Item into a JavaScript Array at a Specific Index?
How to Add an Item to an Array at a Specific Index?
If you're looking to insert an item into an array at a specific index, JavaScript provides the splice method. This method takes three arguments:
For example, consider the following array:
arr = ['Jani', 'Hege', 'Stale', 'Kai Jim', 'Borge'];
To insert the item "Lene" into index 2, use the following code:
arr.splice(2, 0, 'Lene');
This will result in the following array:
arr = ['Jani', 'Hege', 'Lene', 'Stale', 'Kai Jim', 'Borge'];
You can also use the splice method to insert multiple items into an array at a specific index. The following code inserts the items ["Lene", "Ola", "Kari"] into index 2:
arr.splice(2, 0, 'Lene', 'Ola', 'Kari');
This will result in the following array:
arr = ['Jani', 'Hege', 'Lene', 'Ola', 'Kari', 'Stale', 'Kai Jim', 'Borge'];
The splice method is a versatile tool that allows you to manipulate arrays with ease. You can use it to insert, delete, and replace items at specific indices.
The above is the detailed content of How to Insert an Item into a JavaScript Array at a Specific Index?. For more information, please follow other related articles on the PHP Chinese website!