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
Release: 2024-12-20 07:44:10
Original
927 people have browsed it

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'];
Copy after login

To insert the item "Lene" into index 2, use the following code:

arr.splice(2, 0, 'Lene');
Copy after login

This will result in the following array:

arr = ['Jani', 'Hege', 'Lene', 'Stale', 'Kai Jim', 'Borge'];
Copy after login

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');
Copy after login

This will result in the following array:

arr = ['Jani', 'Hege', 'Lene', 'Ola', 'Kari', 'Stale', 'Kai Jim', 'Borge'];
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template