Home >Web Front-end >JS Tutorial >How to Insert an Item into a JavaScript Array at a Specific Index?

How to Insert an Item into a JavaScript Array at a Specific Index?

Linda Hamilton
Linda HamiltonOriginal
2024-12-20 07:44:10929browse

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:

  • index: The position where you want to add the item.
  • deleteCount: The number of items to delete from the array at the index specified. In this case, specify 0 to add without deleting.
  • item: The item you want to insert into the array.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn