Home  >  Article  >  Web Front-end  >  How to delete the first element of jquery array

How to delete the first element of jquery array

青灯夜游
青灯夜游Original
2022-06-09 16:32:325391browse

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);".

How to delete the first element of jquery array

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>

How to delete the first element of jquery array

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>

How to delete the first element of jquery array

[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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn