This document is intended to contribute to readers' understanding of Javascript.
The key to understanding Javascript is to have the insight that...
This last fact might lead to some initial confusion working with arrays in folks coming to Javascript from some other programming languages.
Consder that arrays, like everything else in Javascript, are objects, and as objects they are, in fact, hashtables. This means that array elements can be added and retrieved by name *or* index.
The following creates an indexed array and iterates through it using a numeric index...
myArray = [1, 2, 3] ;
for( i=0; i<myArray.length; i++ )
{
document.writeln( i + ". " + myArray[i] + "<br />" );
}
While this next example assigns and retrieves array elements by name...
myArray = []; // same as myArray = new Array();
myArray["custName"] = "Mickey Mouse";
age = -1;
myArray[age] = 42;
document.writeln( "Customer Name: " + myArray["custName"] + "<br/>" );
document.writeln( "Customer Age: " + myArray[age] + "<br/>" );
document.writeln( "<br/><strong>Looping...</strong> <br/>" );
for( i in myArray )
{
document.writeln( i + ": " + myArray[i] + "<br />" );
}
This last example uses these facts to better understand the Javascript document object. We can iterate over the hashtable properties of this object using the following script. Notice how the for construct has a built-in enumeration facility that allows you to iterate over the document properties...
for( p in document )
{
document.writeln( "<tr><td><strong>" + p + "</strong></td><td>" + document[p] + "</td></tr>" );
}
The output of the script follows...
Name |
Value |
All website content and style authored by: H. Nicholas Nagel, Ph.D. (unless otherwise noted). Copyright (c) 2003-2007, all rights reserved.