Definition and usage
The splice () method is used to insert, delete, or replace elements in an array.
Syntax
ArrayObject. splice (index, howmany, element1,..., elementX)
Parameter description
Index is required. Specifies where to add/delete elements.
This parameter is the subscript of the array element that begins to insert or delete. It must be a number.
Howmany is required. Specifies how many elements should be deleted. It must be a number, but it can be "0 ".
If this parameter is not specified, all elements starting from index to the end of the original array are deleted.
Optional. Specifies the new element to be added to the array. Insert from the subscript indicated by index.
ElementX is optional. You can add several elements to the array.
Return Value
If an element is deleted from an arrayObject, an array containing the deleted element is returned.
Description
The splice () method deletes zero or multiple elements starting from the index and replaces the deleted elements with one or more values declared in the parameter list.
Tips and comments
Note: The splice () method and slice () method have different functions. The splice () method directly modifies the array.
Instance
Example 1
In this example, we will create a new array and add an element to it:
Copy codeThe Code is as follows:
<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 Located in index 2 and add a new element to replace the deleted element:
Copy codeThe Code is as follows:
<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 delete the three elements starting with index 2 ("Thomas") and add a new element ("William") to replace the deleted element:
Copy codeThe Code is as follows:
<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