<%response.buffer=true%> <% yere = year(date()) Response.Expires = 0 %> JavaScript Intro
<arrays>
  spacerspacer

JavaScript Arrays

There are times that we want to create groups of variables, but don't want to (or won't be able to) take the time and trouble to name each variable. For this purpose, we can create groups of related variables called Arrays.

Creating an array, and putting values into the related variables is simple:

var myArray = new Array();

We can then assign values to the array:

myArray[0] = "Huey";
myArray[1] = "Dewey";
myArray[2] = "Louie";

In JavaScript an Array is really an object, and usually the keyword "new". The word Array is a control word, and must be capitalized. The parentheses after the word array allow us to indicate the number of elements (items) in the array. If we leave it empty, the array is made longer as we add more items. We can also declare an array by identifying an empty set of square brackets:

myArray = [];

The square brackets can store the index of the array and if empty, then an array is created that currently stores no items.

The items are added as "elements" of the array, and are associated with a number, starting at zero. Zero based arrays can be confusing, but since computers all start to count at zero, the first number, making 9 the 10th number in our decimal numbering system.

In a standard JS array we can see the current number of items by using a property named length:

var myArray = new Array();
myArray[0] = "Huey";
myArray[1] = "Dewey";
myArray[2] = "Louie";
alert(myArray.length);

We can use the length property above to loop through and view or edit all the elements in the array!

Looping an Array with a for loop: Once we have items in our array we can use a for loop to view all of the items stored in the array:

var myOutput = "Donald's nephews are: ";
for(var x = 0; x < myArray.length; x++){
      myOutput += " " + myArray[x];
}
alert(myOutput);

The example above uses a for loop to show all the elements in the array in an alert. Note that the element of the array can be accessed one at a time, using the array number, in this case x represents the number.

We are able to easily add or subtract items from our array, and to be able to keep the code consistent in this way.

Adding To An Existing Array: We can tack on items to the end of an existing array by using the length inside the square brackets to make the array larger and add more elements:

var myArray = new Array();
myArray[myArray.length] = "Huey";
myArray[myArray.length] = "Dewey";
myArray[myArray.length] = "Louie";
alert(myArray.length);

This is handy when you just want to add to an array and not be bothered by what else might be stored inside already!

Random Numbers: To be able to have more fun with arrays, we will first use the following function to generate random numbers:

function randomNum(n){
var myNum = Math.floor(Math.random()*(n));
return myNum;
}
var myRandomNum = randomNum(5);
alert("My random number is: " + myRandomNum);

This function uses built in JavaScript functions to generate a random number. Our function "encapsulates" (wraps) the JavaScript function, and makes it easier for us to access it's abilities. When we use it to generate a random number, we only need to declare a variable, and equate it to the function, and pass a number into the function (in this case 5). This will generate a random number between 0 and 4 . The number passed to the function will be the maximum.

Note the keyword "return" which indicates what will come OUT of the function! The value of myNum is "returned" and placed into the variable called "myRandomNum", outside of the function.

Once we have generated a random number, we can use this number with an array to display a random "message of the day" or in our case, a "quote" to display to the user:

var quoteArray = new Array();
quoteArray[0] = "A stitch in time saves nine.";
quoteArray[1] = "Four score and 7 years ago.";
quoteArray[2] = "For whom the bell tolls.";
quoteArray[3] = "There once was a man from Calcutta.";
quoteArray[4] = "To thine own self be true";
var x = randomNum(5);
alert("Today's quote is: " + quoteArray[x]);

This code is useful for generating random script, or images, so the user sees more dynamic page content on your site.

Since content that appears or disappears on subsequent reloads of a page could be annoying to a user,remember that it would be better to rotate most content, rather than randomize it, since we don't want users to "lose" what they were trying to read on a page reload. An example of this is the "modRotate" example on the examples page.

The randomized quote here would be better for an image swap, for example, or an advertisement, etc.

Splitting A String into an Array: Forms are used to gather data from users.  The data returns to the server in the form of strings.  We frequently need to "split" strings apart to be able to get to the data inside.  Once we split the string up, we are left with an array.  This is a main reason why we need to be able to work with arrays!

For example, Imagine a form, where a user selects 3 "toppings" on a sundae.  The data is returned to the server in the following format:

Cherry,Banana,Chocolate

The above is a single string.  We can see the 3 words, separated by the comma as our 3 sundae toppings. However, we must split the 3 words up to be able to get to the data.  We can use the JavaScript "split" function to turn this string into an array of the 3 toppings. 

See how the data returns to the server by trying this simple form: Topping Choice Form

The above demo shows how the data appears when it is returned to the server.  In this case, our checkbox element provides the name of the data "toppings", which is the name of the element on the form.  The string that is returned can be thought of in this way:

toppings = "Cherry,Banana,Chocolate";

In order to break up the string into the separate words, we use the split function:

aToppings = toppings.split(",");

Now we have an array named "aToppings" that we can use to loop through to get to the individual toppings:

var myOutput = "The toppings chosen are: ";
for(var x = 0; x < aToppings .length; x++){
      myOutput += " " + aToppings[x];
}
alert(myOutput);

The following example demonstrates how a comma separated string in a form element is split into an array.  In this case, the array is written to the page dynamically, using innerHTML, which is a proprietary method for writing to a web page.  (innerHTML is not supported by all browsers, and is NOT part of the DOM standard).

Note: The example requires the user to enter the data in a single comma separated string inside the text box: Split Nephews

Built In Arrays: Resources and elements accessible via JavaScript are frequently presented to us in sets as arrays. For example, through the BOM (Browser Object Model) we can apprehend all the images, links, forms or frames on a given page as arrays. Here's an example of retrieving an array of all images from a page after it loads:

function imageDetails()
{
      output = '<table align="center" border="1" width="80%"><tr><th>name</th><th>src</th><th>height</th><th>width</th></tr>';

      for(x=0; x< window.document.images.length;x++){
            output += "<tr><td align=right><font color=red>" + window.document.images[x].name + "</font></td>";
            output += "<td><font color=blue>" + window.document.images[x].src + "</font></td>";
            output += "<td><font color=green>" + window.document.images[x].height + "</font></td>";
            output += "<td><font color=orange>" + window.document.images[x].width + "</font></td></tr>";
      }
     output += "</table>";
      myDiv = document.getElementById("output"); //DOM1 access to myDiv
      myDiv.innerHTML = output; //use innerHTML to add replace link with images table
}


Note the reference to window.document.images[x] to identify each image by turn, then the reference to each property, for example the important src attribute. Apprehending the array of images in this way uses the BOM, while the div named output is identified by the DOM via the document.getElementById() method. Click to view the Image Array Demo

When Arrays are Not (JS & Associative Arrays): Many languages, including JavaScript provide the ability to create what appear to be "associative" arrays, in which we control the left side of the array equation (where the integer normally goes) by providing a unique string, for example:

myArray = new Array();
myArray["abc"] = 200;
myArray["xyz"] = 300;

While this looks like what is called an associative array in many languages, this is really done by another technique in JavaScript, using objects to tack on properties. Note the following does the same thing:

myArray = new Array();
myArray.abc = 200;
myArray.xyz = 300;

Problems occur when you use the associative array concept on the above. There is no "length" property to the associative array, because it isn't an array at all but an object with properties attached!

You can find much more about arrays here: Associative Arrays Demystified

Looping The Properties of an Object via For Loop: Since we've seen how an associative array is really not an array but an object, how can we loop through it? Here's an example:

myArray = new Array();
myArray.abc = 200;
myArray.xyz = 300;
var output = "";
for(var myProperty in myArray){
output+= myProperty + ": " + myArray[myProperty] + "\n";
}
alert(output);

Here's a link with more detail about arrays of object properties

Lynda.com Video On Arrays: Here's a video from lynda.com introducing arrays: Lynda.com on JavaScript Arrays

 

   
Print this Page Back To Top

2000- <%=yere%> newMANIC INC, All rights reserved