Java Script Arrays
By Stephen Bucaro
An array is defined as an ordered collection of data. You can visualize an
array as a list, each item in the list being identified by an index number
starting with [0] for the first item.
An array can be used to store data that you allow users to search. This type of
application mimics the behavior of a database program. When designing a script,
consider whether handling the data as an array could have an advantage.
The browser itself creates a number of internal arrays for the html elements
on your webpage. For example, it maintains an array for the links on the
webpage, the first link being identified as document.links[0].
Use the new keyword to create an array. For example to create an array
containing six names of colors you might use the code shown below.
var strColor = new Array(6);
Then to enter data into the array, use statements indicating which index each
string should be assigned to, as shown below.
strColor[0] = "black";
strColor[1] = "blue";
strColor[2] = "green";
strColor[3] = "orange";
strColor[4] = "red";
strColor[5] = "white";
Java Script arrays have a length property. Using the declaration shown above,
the strColor array is explicitly defined to have a length of 6. However,
Java Script arrays are dynamic, so you could leave the length empty, as shown below.
var strColor = new Array();
This allows you to add items to the array at any time. In this case, the length
property starts out with a value of 0. You can assign a value to any index in the
array and the length property will automatically adjust for the new size of the
array. If you know what the data will be, you can declare and initialize the array
at the same time as shown below.
var strColor = new Array("black", "blue", "green", "orange", "red", "white");
• JavaScript 1.2 allows you to construct an array without the new Array keywords, as shown below.
strColor = ["black", "blue", "green", "orange", "red", "white"]
In my opinion, this is bad programming practice because, the new keyword
reminds the programmer that a memory object has been created. Later in the
script, when the data in the array is no longer needed, the programmer may want
to release the memory using the delete keyword.
|