Definition and Usage
The unshift() method adds one or more elements to the beginning of the array and 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 and Comments
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:
<script type="text/javascript"> var arr = new Array() arr[0] = "George" arr[1] = "John" arr[2] = "Thomas" document.write(arr + "<br />") document.write(arr.unshift("William") + "<br />") document.write(arr) </script>
Output:
George,John,Thomas 4 William,George,John,Thomas
Example:
<html> <head> <title>JavaScript Array unshift Method</title> </head> <body> <script type="text/javascript"> var arr = new Array("orange", "mango", "banana", "sugar"); var length = arr.unshift("water"); document.write("Returned array is : " + arr ); document.write("<br /> Length of the array is : " + length ); </script> </body> </html>
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!