To replace an element at a specific index in a Javascript array, you can make use of the splice()
method. The splice()
method modifies the original array by adding or removing elements from it. Here is an example code snippet that replaces an element at index i
in an array arr
with a new element:
index.tsx30 chars2 lines
In the above code snippet, the first argument to splice()
is the index where the replacement is to be made. The second argument specifies the number of elements to be removed, which in this case is 1
. Finally, the third argument is the newElement
that should be inserted at the specified index.
Here is an example usage of this code snippet:
index.tsx247 chars6 lines
In the above example, we replace the element at index 2
(which is "orange"
) with a new element "grapefruit"
. The resulting array is ["apple", "banana", "grapefruit", "peach"]
.
gistlibby LogSnag