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

JavaScript method push() adds one or more elements to the end of an array and returns the new length

黄舟
Release: 2017-11-03 11:19:58
Original
4644 people have browsed it

Definition and Usage

push() method adds one or more elements to the end of the array and returns the new length.

Syntax

arrayObject.push(newelement1,newelement2,....,newelementX)
Copy after login
ParametersDescription
newelement1 Required. The first element to be added to the array.
newelement2Optional. The second element to be added to the array.
newelementXOptional. Multiple elements can be added.

Return value

The new length after adding the specified value to the array.

Description

push() method can add its parameters to the end of arrayObject in sequence. It directly modifies the arrayObject instead of creating a new array. The push() method and pop() method use the first-in-last-pop function provided by the array.

Tips and Comments

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

Tip: To add one or more elements to the beginning of the array, use the unshift() method.

Example

In this example, we will create an array and change its length by adding an element:

<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.push("James") + "<br />")
document.write(arr)

</script>
Copy after login

Output:

George,John,Thomas
4
George,John,Thomas,James
Copy after login

The following are the details of the parameters:

element1, ..., elementN: 元素添加到数组的末尾。
Copy after login

Return value:

Returns the length of the new array.
Example:

<html>
<head>
<title>JavaScript Array push Method</title>
</head>
<body>
<script type="text/javascript">
var numbers = new Array(1, 4, 9);
 
var length = numbers.push(10);
document.write("new numbers is : " + numbers ); 
 
length = numbers.push(20);
document.write("<br />new numbers is : " + numbers ); 
</script>
</body>
</html>
Copy after login

This will produce the following results:

new numbers is : 1,4,9,10
new numbers is : 1,4,9,10,20
Copy after login


The above is the detailed content of JavaScript method push() adds one or more elements to the end of an array and returns the new length. 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