Array Power, Part I - DHTML Lab | 3 | WebReference

Array Power, Part I - DHTML Lab | 3

Logo

Array Power, Part I
unshift()


The unshift() method
adds one or more elements to the front of an array and returns the new length of the array.

For example, let's create an array called myArray with three elements:

myArray = [0,"cat",true];, or
myArray = new Array(0,"cat",true);

Now, we want to insert a new string element, "dog", to the beginning of myArray, and we want to store the length of the updated array in a variable called arLength.

Without unshift()

If the unshift() method is unavailable, we can insert the new element to the front of the array with these statements:

Statement usedmyArray becomes
1.myArray.reverse();[true,"cat",0]
2.myArray[myArray.length] = "dog";[true,"cat",0,"dog"]
3.myArray.reverse();["dog",0,"cat",true]
4.arLength = myArray.length; 

We use the built-in reverse() method to transpose the array elements. The first element is now the last element. Then we add the new element to the end of the array. Next, we transpose the array again, making the new last element the first one. Finally, we get the array's length from its length property and assign it to arLength.

With unshift()

Using unshift() we can add the new element, and get the array length with a single statement:

arLength = myArray.unshift("dog");

If we wanted to add two elements, "dog" and "mouse", to myArray, we could still do it with one statement:

arLength = myArray.unshift("dog","mouse");

myArray would then look like this:

["dog","mouse",0,"cat",true]

So far we can only use unshift() with Navigator. Let's now make it available to Explorer.


Produced by Peter Belesis and

All Rights Reserved. Legal Notices.
Created: April 26, 2000
Revised: April 26, 2000

URL: http://www.webreference.com/dhtml/column31/3.html