spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / experts / dhtml / column31
Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

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

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business

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

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