Splice in JavaScript is mainly used to operate arrays in js, including deleting, adding, replacing, etc.
Note: This method will change the original array! .
1. Delete - used to delete elements, two parameters, the first parameter (the position of the first item to be deleted), the second parameter (the number of items to be deleted)
2. Insert - Insert any element into the specified position in the array. Three parameters, the first parameter (insertion position), the second parameter (0), the third parameter (inserted item)
3. Replacement - insert any item element into the specified position of the array, and at the same time Remove any number of items, three arguments. The first parameter (starting position), the second parameter (the number of items to be deleted), the third parameter (to insert any number of items)
Example:
1. Delete function , the first parameter is the position of the first item, and the second parameter is the number to be deleted.
array.splice(index,num), the return value is the deleted content, and array is the result value.
eg:
<!DOCTYPE html> <html> <body> <script> var array = ['a','b','c','d']; var removeArray = array.splice(0,2); alert(array);//弹出c,d alert(removeArray);//返回值为删除项,即弹出a,b </script> </body> </html>
2. Insert function, the first parameter (insertion position), the second parameter (0), the Three parameters (insert items)
array.splice(index,0,insertValue), the return value is an empty array, and the array value is the final result value
eg:
<!DOCTYPE html> <html> <body> <script> var array = ['a','b','c','d']; var removeArray = array.splice(1,0,'insert'); alert(array);//弹出a,insert,b,c,d alert(removeArray);//弹出空 </script> </body> </html>
3. Replacement function, first parameter (starting position), second parameter (number of items to delete), third parameter (insert any number of items) )
array.splice(index,num,insertValue), the return value is the deleted content, and array is the result value.
eg:
<!DOCTYPE html> <html> <body> <script> var array = ['a','b','c','d']; var removeArray = array.splice(1,1,'insert'); alert(array);//弹出a,insert,c,d alert(removeArray);//弹出b </script> </body> </html>
The above is a detailed explanation of the splice method in JavaScript introduced by the editor. I hope it will be useful to everyone. Help, if you have any questions please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!
For more detailed explanations of the usage of the splice method in JavaScript, please pay attention to the PHP Chinese website!