Web Developer

JavaScript Arrays

Arrays are a programming construct available in most programming languages.  Essentially, they are an organizational feature that allows you to access the elements of the array by number rather than by name.  In JavaScript, arrays can contain any kind of data - including objects.  We'll take advantage of this fact a little later on.

If you've ever been to a deli, you'll understand the concept of arrays.  At the deli (at least mine!) you typically walk in, take a number, then wait until your number is called.  When your number is called, you give your order to the butcher, often one item at a time.  The butcher doesn't have to know your name to process your order.  He only cares that he's processing the order he should by keeping track of the number.

The concept is exactly the same as an array.  If we consider the butcher as the function that makes use of an array of customers simply by knowing their number, then we've almost got it.  The butcher calls a number, then deals with the items (properties), then moves on to the next number.  And that's exactly how an array works!  The line of customers is the array, each individual customer is an element of the array, and the order is the data stored in each element.

Creating Arrays in JavaScript

Creating an array in JavaScript is simple - just call the built-in Array() function:

var customers = new Array();

Then you access each customer in the array by the index number.  The first element of the array is customers[0], the next customers[1] and so on.  Arrays in JavaScript are 0 based - the first element is always 0, not 1.  To assign data to the elements of the array, just refer to the element by its index like any other object:

customers[0].firstOrder = 'ham';
customers[0].secondOrder = 'salami';
customers[1].firstOrder = 'turkey';

Sounds pretty simple doesn't it?  How do you knowhow many elements are in the array?  Simple again.  Each array contains a length property that holds the number of elements.  The length property will always be one more than the index of the last element (remember that arrays are 0 based!).  Using the above example, the length property of the customers array would be 2.  You might be wondering if there is some pre-defined limit to the number of elements in an array.  The short answer is not really.  Arrays are only bound by the amount of memory on the computer that's using them (your users' computers - that's where the array will be processed).  Since you don't have any control over that, don't worry about it.  Just try not to create arrays that are so huge that no one will be able to handle them!  Finally, most programmers wonder if they can change the number of elements in an array.  The answer to that question is yes - and in JavaScript you simply add the next element onto the end of the array.  In Java, for example, arrays must have finite bounds.

A Useful Example - The Jump List

Let's see if we can create a useful example that uses arrays.  We'll create a dropdown box that, when clicked on will navigate to a specified page.  Here is the code we'll need.  We'll analyze it later:

<html>
<head>
<title>JumpList</title>
<script language="JavaScript">
var urls = new Array();
urls[0] = '';
urls[1] = 'http://www.yahoo.com';
urls[2] = 'http://www.av.com';
urls[3] = 'http://www.hotbot.com';
urls[4] = 'http://www.lycos.com';
urls[5] = 'http://www.google.com';

function goSearch(form){
i = form.JumpList.selectedIndex;
if(i!=0)
window.location.href = urls[i];
}

</script>
</head>
<body>
<form>
<p><select size="1" name="JumpList" onChange="goSearch(this.form)">
<option>Select a Search Engine</option>
<option>Yahoo</option>
<option>AltaVista</option>
<option>Hotbot</option>
<option>Lycos</option>
<option>Google</option>
</select></p>
</form>
</body>
</html>

That was pretty easy!  Let's take it a line at a time.  First, we must create the array to hold the URLs that we'll jump to.  Just create an array using the Array() constructor.  Then, we populate the array with elements that contain the URLs as their data.  Our array contains 6 elements and the first URL is empty.  If the user selects the first item in our list box nothing happens.  Second, we create the the goSearch() function.  This function takes a form as an argument and then looks for an element named JumpList in the form.  We assign a variable the index of the item selected in JumpList, then tell the window object to load the URL specified by the index in our array.  Finally, we set up a <select> element in the body of our document that contains labels for each of the URLs and capture the onChange event to run the goSearch() function.  Notice the first label is merely an instructional placeholder and that's why we assign an empty String to the first element in our array.  You can see this one in action on the Source Code Page.

Arrays on the Fly

Let's see if we can modify our JumpList example above to make our arrays more general.  Along the way, we'd like to force our arrays to do more of the work in creating our web pages.  If we want to create generalized arrays, then it makes sense to create a function that will create an array from the arguments supplied.  This array constructor is what makes our arrays general.  Then, we'll create two arrays using our new constructor - one for the labels, one for the URLs.  Finally, we'll write a script inside our body element that will actually write the <select> element for us.  We won't, however, need to modify the goSearch() function; it will perform the same action as our previous example.  Here's the code that we'll analyze a little later:

<html>
<head>
<title>JumpList2</title>
<script language="JavaScript">
function jumpArray(){
var args = jumpArray.arguments;
for(var i=0; i<args.length; i++)
this[i] = args[i];
this.length = args.length;
}

var labels = new jumpArray('Select a Search Engine', 'Yahoo', 'AltaVista', 'Hotbot','Lycos', 'Google');

var urls = new jumpArray('','http://www.yahoo.com', 'http://www.av.com', 'http://www.hotbot.com', 'http://www.lycos.com', 'http://www.google.com');

function goSearch(form){
i = form.JumpList.selectedIndex;
if(i!=0)
window.location.href = urls[i];
}
</script>
</head>
<body>
<!-- The select menu will appear wherever the following script is placed -->
<script language="JavaScript">
document.write('<form><select name="JumpList" onChange="goSearch(this.form)">');
for(var i=0;i<labels.length; i++)
document.write('<option>' + labels[i]);
document.write('</select></form>');
</script>
</body>
</html>

OK, this example is a little more complicated so let's take it a section at a time.  First we create our generic array maker.  The jumpArray function loops through the arguments array and assigns each argument to an element in the array.  It then makes sure that the length of the resulting array is assigned the length of the array of arguments passed.  Next, we create two jumpArrays - one for the labels and one for the URLs.  Finally, we add the unchanged goSearch() function.

Later on, we add our first script to a <body> element.  This script  writes the HTML needed to create the <form> element as well as creates the <select> element using the document.write() method.  Finally, we populate the <select> element with <option> elements that we get from the labels array and close both the <select> and <form> elements.  Since this script is the first content of the <body> element, it gets printed at the top of the page.  In fact, we could include our JumpList anywhere we want simply by specifying the script where we want the JumpList to be located.  You can see it in action on the Source Code page.

This example, although more complex, demonstrates the power of the array mechanism.  Even though our code was more extensive, I hope you can see that had the arrays been larger, this is definitely the way to go.  Rather than type in all of the <option> elements, we simply used an existing construct - the labels array.