Home  >  Article  >  Web Front-end  >  JavaScript method shift() to delete the first element in an array and return the value of the first element

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

黄舟
黄舟Original
2017-11-03 13:14:413869browse

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()

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>

Output:

George,John,Thomas
George
John,Thomas


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

Syntax

array.shift();

The following are the details of the parameters:

NA

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>

This will produce the following results:

Removed element is : 105

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!

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