Splice in JavaScript is mainly used to operate on arrays in js, including deletion, addition, replacement, etc.
Note: This method changes 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 item element to the specified position of the array. Three parameters, the first parameter (insert position), the second parameter (0), and the third parameter (insert item)
3. Replace - Insert any item element into the specified position of the array, and delete any number of items at the same time, three parameters. The first parameter (start position), the second parameter (number of items deleted), and the third parameter (insert any number of items)
Example:
1. Delete function. The first parameter is the first position and the second parameter is the number of deleted.
array.splice(index,num), the return value is deleted, 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);//Pop c,d alert(removeArray);//Return value is the delete item, that is, a,b </script> </body> </html>
2. Insert function, the first parameter (insert position), the second parameter (0), and the third parameter (insert item)
array.splice(index,0,insertValue), return value is an empty array, 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);//Pop up a,insert,b,c,d alert(removeArray);//Pop up empty</script> </body> </html>
3. Replacement function, the first parameter (start position), the second parameter (number of deleted items), and the third parameter (insert any number of items)
array.splice(index,num,insertValue), the return value is deleted, 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);//Pop up a,insert,c,d alert(removeArray);//Pop up b </script> </body> </html>
The above is a detailed explanation of the usage of splice methods in JavaScript introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!