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

黄舟
Release: 2017-11-04 09:37:32
Original
15595 people have browsed it

Definition and Usage

The unshift() method adds one or more elements to the beginning of thearrayand returns the new length.

Syntax

arrayObject.unshift(newelement1,newelement2,....,newelementX)
Copy after login
Parameters Description
newelement1 Required. The first element added to the array.
newelement2 Optional. The second element added to the array.
newelementX Optional. Several elements can be added.

Return value

The new length of arrayObject.

Description

The unshift() method will insert its parameters into the head of arrayObject and move existing elements to higher subscripts sequentially to leave space . The first argument to the method will become the new element 0 of the array, if there is a second argument it will become the new element 1, and so on.

Please note that the unshift() method does not create a new creation, but directly modifies the original array.

Tips andComments

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

Note: The unshift() method does not work correctly in Internet Explorer!

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

Example

In this example, we will create an array, add an element to the beginning of the array, and return the new length of the array:

Copy after login

Output:

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

Example:

  JavaScript Array unshift Method 
    
Copy after login

This will produce the following results:

Returned array is : water,orange,mango,banana,sugar Length of the array is : 5
Copy after login


The above is the detailed content of JavaScript method unshift() adds one or more elements to the beginning 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
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!