JavaScript's Splice method allows you to delete or insert elements from an array, returning a new array containing the deleted elements. The usage is as follows: Delete elements: arr.splice(start, deleteCount) Insert elements: arr.splice(start, 0, ...items) Replace elements: arr.splice(start, 1, ...items) Delete from the end Element: arr.splice(-1, deleteCount)Delete element from the beginning: arr.splice(0, deleteCount)
Splice method in JavaScript Usage
The Splice method is a built-in method of the Array object in JavaScript, used to delete or insert elements from the array. It returns a new array containing the deleted elements, and new elements can be inserted in the original order.
Syntax
<code class="js">array.splice(start, deleteCount, ...items)</code>
Parameters
Return value
A new array containing the deleted elements.
How to remove elements using
:
<code class="js">const arr = [1, 2, 3, 4, 5]; arr.splice(2, 2); // [3, 4]</code>
Insert element:
<code class="js">arr.splice(2, 0, 'a', 'b'); // [1, 2, 'a', 'b', 3, 4, 5]</code>
Replace element:
Delete element and insert new element, which is equivalent to replacement operation:
<code class="js">arr.splice(2, 1, 'c'); // [1, 2, 'c', 4, 5]</code>
Remove elements from the end of the array:
Use a negative starting position:
<code class="js">arr.splice(-1, 1); // [1, 2, 'c', 4]</code>
Remove elements from the beginning of the array :
Specify the starting position as 0:
<code class="js">arr.splice(0, 1); // [2, 'c', 4]</code>
Note
The above is the detailed content of How to use splice in js. For more information, please follow other related articles on the PHP Chinese website!