background
|
|
Linux
Linux Support
A small area on the internet for Linux Support.
More icon

Computer
|
|
Up Image
Navigation
Search this Site
Enter your search terms

Site Breadcrumb - You are here
|
Thau's JavaScript Tutorial
Lesson 4

by Thau!

Page 8 — Arrays

We've seen that variables can hold numbers, strings, and references to objects. There's one more kind of information that JavaScript understands: arrays.

Arrays are lists. You might have a list of URLs that you want to visit, a list of names that you want to remember, or a list of colors in which you'd like text displayed. All these lists can be stored in arrays.

Here's how to create an array of colors:

var colors = new Array("red","blue","green");

Now that you have an array, what can you do with it? The good thing about arrays is that elements of an array can be accessed by number. The first element is number 0 and can be accessed like this:

var the_element = colors[0];

After you execute this line of JavaScript, the variable the_element will hold the string "red." As you can see, you access the first element of an array by writing the name of the array and putting the element's number in square brackets. The second element of an array is number 1.

Once you've created an array, you can add to and change its values. If you decided to change the first element of the colors array to purple instead of red, you could write this:

colors[0] = "purple";

Arrays are often used in tandem with loops. Check out this example of arrays and loops.

next page»