Home > Web Front-end > JS Tutorial > body text

JavaScript method shift() to delete the first element in an array and return the value of the first element

黄舟
Release: 2017-11-03 13:14:41
Original
3906 people have browsed it

Definition and usage

The shift() method is used to delete the first element of the array from it and return the value of the first element.

Syntax

arrayObject.shift()
Copy after login

Return value

The value of the original first element of the array.

Explanation

If the array is empty, the shift() method will do nothing and return an undefined value. Please note that this method does not create a new array, but directly modifies the original arrayObject.

Tips and Comments

Comments: This method will change the length of the array.

Tip: To remove and return the last element of an array, use the pop() method.

Example

In this example, we will create an array and delete the first element of the array. Note that this will also change the length of the array:

<script type="text/javascript">

var arr = new Array(3)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"

document.write(arr + "<br />")
document.write(arr.shift() + "<br />")
document.write(arr)

</script>
Copy after login

Output:

George,John,Thomas
George
John,Thomas
Copy after login


JavaScript Arrayshift() method deletes an array the first element in and returns that element.

Syntax

array.shift();
Copy after login

The following are the details of the parameters:

NA
Copy after login

Return value:

Returns a single value removed from the array.

Example:

<html>
<head>
<title>JavaScript Array shift Method</title>
</head>
<body>
<script type="text/javascript">
var element = [105, 1, 2, 3].shift();
document.write("Removed element is : " + element ); 
</script>
</body>
</html>
Copy after login

This will produce the following results:

Removed element is : 105
Copy after login

The above is the detailed content of JavaScript method shift() to delete the first element in an array and return the value of the first element. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!