Javascript Tutorial -- Using Arrays
One of the many uses of Javascript is making dynamic web pages -- that is web pages that change graphics or text in response to user input. While we will get to dynamic HTML documents in the "Advanced Javascript" section, this lesson will introduce a concept that is a necessary building block for many of these advanced techniques: Arrays.
Suppose, for instance, that you wanted to create an image gallery on the web, and you wanted users to be able to click a button to change from one image to the next on the web page. We learned in Lesson 3 how to store data in variables. However, we can only store one item at a time in any given variable. What happens if you need to store a list of data, like a list of URL's for images on your web server? This is precisely what an array is: a way of linking several variables together using an index to reference which variable you wish to use. Think of an array as being like mailboxes at the post office. Any given mailbox is like a variable, but if you want to specify your mailbox, you reference it with your P.O. box number.
Here is how you declare an array variable in Javascript:
<script type="text/javascript">
<!--
var List = new Array()
//-->
</script>
If you notice, the declaration for an array is a little different than the declaration for a garden-variety, plain-vanilla variable. That's because in Javascript, an array is an "object". A complete discussion of object-oriented programming is beyond the scope of this tutorial, but for now, suffice it to say that an object is a way of grouping particular functions (called "methods") and data together in a logical way. Remember when we first used the "document.write" method? In Javascript, the HTML document you are working with is a type of object, and the "write" function is a method of the document object -- it is a function that is tied to the document object that allows you to print text or HTML tags to the document object. When you create a new array in Javascript, you are using the Array() method (function) to create a new array object in the HTML document. Once you get used to it, it's really not a difficult concept, but if you've never done any object-oriented programming, it might take a little while to get used to the idea. If you are having trouble wrapping your head around the idea of objects, don't worry about it for now -- just remember the syntax for creating a new array is a little different than an ordinary variable, and that there will be a few differences is how you use an array.
Probably the easiest way to start getting comfortable with array objects is to start using them in an example, so let's go back to our example of creating an image gallery. Like I said earlier, dynamic content is a little too advanced for right now, but rather than creating a single image that changes dynamically in response to user input, how about creating a simple list of images and using the "document.write" method to display all of them as thumbnail images? Here's one way you could accomplish that task:
<script type="text/javascript">
<!--
//Declare the array:
var List = new Array()
//Declare an index
var i
//Define each element in the array (notice that you have to index
//each element, and that the index is enclosed in square brackets)
List[0] = "blackslate.gif"
List[1] = "bluegranite.gif"
List[2] = "blueswirl.gif"
List[3] = "ceramic.gif"
List[4] = "crackle.gif"
//Print each image to the web browser (notice we are using the
//concatenation operator from lesson 4 to append the image name
//to the URL in the document.write method and that we are using
//a for loop to step through each element in the array)
for(i = 0; i <= 4; i++)
{
document.write('<img src="/images/Backgrounds/"' + List[i] + '">'); }
//-->
</script>
One problem when working with arrays in any programming language is knowing when you have referenced the last element in an array. In the example above, to add new images to the array, you must add a new array element and then you must modify the for loop so that it includes the new element in the iteration. Even worse, suppose you want to create a script that has a list of images in an XML file (for example, from an RSS feed). In this case, it would be impossible to hard-code the number of elements in the array before-hand, since there could conveivable be any number of images (or whatever) in your array. Fortunately, Javascript has a better way of doing things.
As I mentioned earlier, arrays are Javascript objects, and one feature of an object is that there are frequently a number of methods included in the object definition that allow you to manipulate the object in a number of ways. In the array object, one such method is the "length" method, which tells you how many elements there are in the array. Therefore, the for loop in the example above can be rewritten to make the script more flexible. If you want to add a new element to the array, you only have to add the code to define the new element; you don't have to modify the for loop if you use the "length" method. Here's how you do it:
...
for(i=0; i < List.length(); i++)
...
Now, no matter how many elements are in your array, no matter if you know how many elements will be contained in your array or if you are reading a list items from a database, you will always loop through each item in your array. Here's the full code for a listing of images using the "length" method:
<script type="text/javascript">
<!--
//Declare the array:
var List = new Array()
//Declare an index
var i
//Define each element in the array (notice that you have to index
//each element, and that the index is enclosed in square brackets)
List[0] = "blackslate.gif"
List[1] = "bluegranite.gif"
List[2] = "blueswirl.gif"
List[3] = "ceramic.gif"
List[4] = "crackle.gif"
//Print each image to the web browser (notice we are using the
//concatenation operator from lesson 4 to append the image name
//to the URL in the document.write method and that we are using
//a for loop to step through each element in the array)
for(i = 0; i < List.length(); i++)
{
document.write('<img src="/images/Backgrounds/"' + List[i] + '">')
}
//-->
</script>
Here is a slightly more complete version of the script above -- it has all of the required attributes of the <img> tag that I omitted for brevity in the example above, and it also lists the names of the thumbnails below the images.