unshift

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.

Returns

The new length property of the object upon which the method was called.

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

See Also

Tags (0)

Edit tags
  • No tags

Attachments (0)

 

Attach file