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)
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:
Output:
George,John,Thomas 4 William,George,John,Thomas
Example:
JavaScript Array unshift Method
This will produce the following results:
Returned array is : water,orange,mango,banana,sugar Length of the array is : 5
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!