Definitions and usage
The splice () method inserts, deletes, or replaces the elements of an array.
Grammar
Arrayobject.splice (index,howmany,element1,....., elementx)
Parameter description
Index required. Specify where to add/remove elements from.
This parameter is the subscript for the array element that starts inserting and/or deleting, and must be a number.
Howmany required. Specify how many elements should be deleted. Must be a number, but it can be "0".
If this parameter is not specified, all elements that start from index to the end of the original array are deleted.
Element1 Optional. Specify the new element to add to the array. Start the insertion at the lower mark that is indicated by index.
Elementx Optional. You can add several elements to an array.
return value
If an element is removed from the Arrayobject, an array containing the deleted elements is returned.
Description
The splice () method deletes 0 or more elements starting at index, and replaces the deleted elements with one or more values declared in the argument list.
Tips and comments
Note: Notice that the splice () method is different from the slice () method, and the splice () method is modified directly to the array.
Instance
Example 1
In this case, we'll create a new array and add an element to it:
Copy Code code 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 (A RR + "<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:
Copy Code code 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 (A RR) </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 Code code 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 (A RR) </script>
Output:
George,john,thomas,james,adrew,martin George,john,william,martin