Two methods: 1. Use shift() to delete the first element. The syntax is "array object.shift();". This method will return the value of the element after deleting the first element of the array. 2. Use splice() to delete the first element. splice() can delete the specified number of elements starting from the specified position. Just set the starting position to 0 and the number to delete to 1. The syntax is "array object. splice(0,1);".
The operating environment of this tutorial: windows7 system, jquery3.6.0 version, Dell G3 computer.
There are two ways to delete the first element in an array in jquery:
Use shift()
Use splice()
Method 1: Use shift() to delete the first element
The shift() method is used to Removes the first element of the array from it and returns the value of the first element.
Note: This method changes the length of the array!
<!doctype html> <html> <head> <meta charset="UTF-8"> <script src="./js/jquery-3.6.0.min.js"></script> </head> <body> <script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log(fruits); fruits.shift(); console.log(fruits); </script> </body> </html>
Method 2: Use splice() to delete the first element
The splice() method is used to insert, delete or Replace elements of an array.
Delete syntax:
splice(index,1)
The first parameter index is the position of the element to be deleted in the array, and the second parameter is the number to be deleted (because only the first element needs to be deleted, Therefore the quantity is 1).
<!doctype html> <html> <head> <meta charset="UTF-8"> <script src="./js/jquery-3.6.0.min.js"></script> </head> <body> <script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log(fruits); fruits.splice(0,1); console.log(fruits); </script> </body> </html>
[Recommended learning: jQuery video tutorial, web front-end video】
The above is the detailed content of How to delete the first element of jquery array. For more information, please follow other related articles on the PHP Chinese website!