Avatar ·

How to insert an element into a JavaScript array at a specific position?

Hello everyone! I just started learning JavaScript and encountered a problem when working with arrays. I need to insert a new element into an array not at the end and not at the beginning, but at a specific index, for example, between the second and third element.

\n\n

I know about the push() and unshift() methods, but they only add elements to the end or beginning. I tried using splice(), but it didn't work — either I misunderstood the syntax or I'm doing something wrong.

\n\n

Here's an example of my situation: I have an array with names ['Ivan', 'Maria', 'Petr'], and I need to insert the name 'Anna' between Maria and Petr, so that it becomes ['Ivan', 'Maria', 'Anna', 'Petr']. How to do this correctly?

\n\n

I would be grateful for a detailed explanation with an example.