Home  >  Article  >  Web Front-end  >  JavaScript method push() adds one or more elements to the end of an array and returns the new length

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

黄舟
黄舟Original
2017-11-03 11:19:584616browse

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)
Parameters Description
newelement1 Required. The first element to be added to the array.
newelement2 Optional. The second element to be added to the array.
newelementX Optional. 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>

Output:

George,John,Thomas
4
George,John,Thomas,James

The following are the details of the parameters:

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

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>

This will produce the following results:

new numbers is : 1,4,9,10
new numbers is : 1,4,9,10,20


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!

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