Array Power, Part II - DHTML Lab | 2 | WebReference

Array Power, Part II - DHTML Lab | 2

Logo

Array Power, Part II
push()


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

To demonstrate, we'll use our trusty example array called myArray, with three elements:

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

Now, two new string elements, "dog" and "mouse" are called for. We want to append them to the end of myArray, and we want to store the length of the updated array in a variable called arLength.

Without push()

If the push() method is unavailable, we can append the new elements to the end of the array with these statements:

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

Not many statements, to be sure. For every element that needs to be added to the array, we append it using myArray[myArray.length], and then get the array's length from its length property and assign it to arLength.

However, it is still not as elegant as using push(), especially if we had many elements to append.

With push()

Using push() we can append the new elements, and get the array length with a single statement:

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

myArray would then look like this:

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

Although the push() method is available in all releases of Navigator 4, its functionality is different in later versions.


Produced by Peter Belesis and

All Rights Reserved. Legal Notices.
Created: May 2, 2000
Revised: May 2, 2000

URL: https://www.webreference.com/dhtml/column32/2.html