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

Array Power, Part I - DHTML Lab | 6


Array Power, Part I

The shift() method
removes the first element from an array and returns that element.

For example, let's use myArray from the previous examples:

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

We want to remove the first element from myArray, truncating myArray, and assign it to a variable we'll call numeroUno.

Without shift()

We can remove the first element with these statements:

Statement usedmyArray becomes
1.numeroUno = myArray[0]; 
3.myArray.length = Math.max(myArray.length-1,0);[true,"cat"]

First we assign the value of the first element to numeroUno. That part is easy. Then we have to remove the element, so we once again use the built-in reverse() method to transpose the array elements. Now the first element, the element we want to remove, is the last element. We can easily remove it by decrementing the length property of the array. Notice that we make sure that the minimum length of myArray is 0. If we started with an empty array, we do not want to set the length to -1! Lastly, we transpose the now shorter array again, placing the elements in their correct order.

With shift()

The first element can be removed, and assigned, with a single statement:

numeroUno = myArray.shift();

myArray would then look like this:


Ok, let's prototype shift() for use with Explorer.

Produced by Peter Belesis and

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