
1.splice() syntax
1 | arrayObject.splice(index,deleteCount,item1,.....,itemX)
|
Copy after login
##index : Specify the starting position of modification (counting from 0)
deleteCount: Indicates the number of array elements to be deleted.
item1,...,itemX: The elements to be added to the array start from the
index position. If not specified,
splice() will only remove array elements.
Return value: an array composed of the deleted elements. If only one element was removed, an array containing only one element is returned. If no elements were removed, an empty array is returned.
2. Usage example
Deleting array elements:
1 2 3 4 5 6 7 8 9 10 11 | <script>
arr1=[9,2,6,4,5];
res1=arr1.splice(2);
console.log(res1);
console.log(arr1);
arr2=[9,2,6,4,5];
res2=arr2.splice(2,2);
console.log(res2);
console.log(arr2);
</script>
|
Copy after login
Adding new array elements:
1 2 3 4 5 6 7 8 9 | <script>
arr3=[9,2,6,4,5];
console.log(arr3);
result=arr3.splice(1,0,99,10);
console.log(arr3);
result=arr3.splice(2,0,...[111]);
console.log(arr3);
</script>
|
Copy after login
Deleting array elements:
1 2 3 4 5 | <script>
arr4=[1,2,3,4,5];
res=arr4.splice(1,3,...[88,99,44]);
console.log(arr4);
</script>
|
Copy after login
Recommended: "
2021 js interview questions and answers (large summary)"
The above is the detailed content of Correct use of splice() in Javascript. For more information, please follow other related articles on the PHP Chinese website!