JavaScript splice of method

  • 2020-03-27 00:00:48
  • OfStack

Definition and usage
The splice() method is used to insert, delete, or replace elements of an array.
grammar
ArrayObject. Splice (index, howmany, element1,... , elementX)
Parameters to describe
The index required. Specifies where to add/remove elements.
This parameter is the index of the array element that was started to be inserted and/or deleted, and must be a number.

Howmany required. Specifies how many elements should be deleted. It has to be a number, but it can be a zero.
If this parameter is not specified, all elements from the beginning of index to the end of the original array are deleted.

Element1 is optional. Specifies the new element to be added to the array. Insert from index.
ElementX optional. You can add several elements to an array.
The return value
If an element is deleted from an arrayObject, an array of the deleted elements is returned.
instructions
The splice() method deletes zero or more elements starting at index and replaces those elements with one or more values declared in the argument list.
Hints and comments
Note that the splice() method works differently from the slice() method, which directly modifies the array.
The instance
Example 1
In this example, we will create a new array and add an element to it:

<script type="text/javascript"> var arr = new Array(6) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" arr[3] = "James" arr[4] = "Adrew" arr[5] = "Martin" document.write(arr + "<br />") arr.splice(2,0,"William") document.write(arr + "<br />") </script>

Output:
George, John, Thomas, James, Adrew, Martin, George, John, William, Thomas, James, Adrew, Martin
Example 2
In this example we will delete the element at index 2 and add a new element to replace the deleted element:

<script type="text/javascript"> var arr = new Array(6) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" arr[3] = "James" arr[4] = "Adrew" arr[5] = "Martin" document.write(arr + "<br />") arr.splice(2,1,"William") document.write(arr) </script>

Output:
George, John, Thomas, James, Adrew, Martin, George, John, William, James, Adrew, Martin
Example 3
In this example we will remove the three elements starting from index 2 ("Thomas") and add a new element ("William") to replace the deleted element:

<script type="text/javascript"> var arr = new Array(6) arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" arr[3] = "James" arr[4] = "Adrew" arr[5] = "Martin" document.write(arr + "<br />") arr.splice(2,3,"William") document.write(arr) </script>

Output:
George, John, Thomas, James, Adrew, Martin, George, John, William, Martin

Related articles: