In JavaScript, you can insert an element into an array at a specific index using the splice method. The splice method is a mutable operation, which means the original array is modified.
Here's an example:
index.tsx145 chars7 lines
In the above example, we first declare an array myArray
with elements [1, 2, 3, 4, 5]
. The splice method is then called on this array, passing in the index at which we want to insert the new value (in this case, 2), how many elements we want to remove (in this case, 0), and the value we want to insert (in this case, 6).
After running this code, myArray
is now [1, 2, 6, 3, 4, 5]
.
gistlibby LogSnag