Array Power, Part I - DHTML Lab | 3
Array Power, Part I
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.
If the unshift() method is unavailable, we can insert the new element to the front of the array with these statements:
|Statement used||myArray becomes|
|2.||myArray[myArray.length] = "dog";||[true,"cat",0,"dog"]|
|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.
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:
So far we can only use unshift() with Navigator. Let's now make it available to Explorer.
Produced by Peter Belesis andAll Rights Reserved. Legal Notices.
Created: April 26, 2000
Revised: April 26, 2000