The splice() method adds or removes items from the array and then returns the deleted item. This method will change the original array. The syntax is [arrayObject.splice(index,howmany,item1,.... .,itemX)].
The splice() method in JS is:
1. Definition and usage
splice()
The method adds/removes items from the array and then returns the deleted item.
Note: This method will change the original array.
2. Syntax
arrayObject.splice(index,howmany,item1,.....,itemX)
3. Description
splice()
Method removes zero or more elements starting at index
and replaces those removed elements with one or more values declared in the parameter list.
If an element is deleted from arrayObject
, the array containing the deleted element is returned.
5. Example
Example 1
In this example, we will create a new array and add it to Add an 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,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 Elements:
<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
Related learning recommendations: javascript video tutorial
The above is the detailed content of What is the splice() method in JS?. For more information, please follow other related articles on the PHP Chinese website!