Table of contents
- 1. Summary
- 2. Syntax
- 3. Parameters
- 4. Returns
- 5. Description
- 6. Examples
- 7. See Also
Summary
Adds one or more elements to the beginning of an array and returns the new length of the array.
Method of Array | |
|---|---|
| Implemented in | JavaScript 1.2 |
| ECMAScript Edition | ECMAScript 3rd Edition |
Syntax
arrayName.unshift(element1, ..., elementN)
Parameters
element1, ..., elementN- The elements to add to the front of the array.
Description
The unshift method inserts the given values to the beginning of an array-like object.
unshift is intentionally generic; this method can be called or applied to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.
Examples
Example: Adding elements to an array
The following code displays the myFish array before and after adding elements to it.
// assumes a println function exists
myFish = ["angel", "clown"];
println("myFish before: " + myFish);
unshifted = myFish.unshift("drum", "lion");
println("myFish after: " + myFish);
println("New length: " + unshifted);
This example displays the following:
myFish before: ["angel", "clown"] myFish after: ["drum", "lion", "angel", "clown"] New length: 4