Java All-in-One For Dummies
Book image
Explore Book Buy On Amazon

In JavaScript, arrays are a kind of collection. You can work with arrays to integrate JavaScript with HTML. Each array contains zero or more like items that you can manipulate as a group.

How to create an array in JavaScript

JavaScript provides three methods for creating arrays: regular, condensed, and literal. In general, one way is as good as another. Of the three, the regular method shown in the following listing is the easiest to understand, but the literal method is the most compact.

  

Creating Arrays

Regular:

Condensed:

Literal:

All three methods produce precisely the same array. The regular method creates the array first and then assigns strings to each array element by number. The square brackets behind Colors indicate the element number, which begins at 0 and increments by 1 for each element you add.

Notice that when using the condensed method you enclose the array elements in parentheses as part of the constructor. However, when using the literal method, you enclose the array elements in square brackets.

image0.jpg

How to access array members

Each array member has a unique number — an address of sorts. You access array members by providing the array name and then the element number within square brackets. Normally, you use a loop to access array members. Loops are a means of automating array access.

The following code shows an example of how you might access an array, one element at a time, and display its content.

  

Access Array Elements

This example uses a for loop. The for loop creates a counter variable (a number) named i that begins at 0 (the first element of the array) and continues to increment (i++) until it has accessed all the array elements (i < Colors.length). The document.write() function outputs the Colors element number, the content (as Colors[i] where i is the element number), and an end-of-line tag.

image1.jpg

About This Article

This article is from the book:

About the book author:

Doug Lowe still has the electronics experimenter's kit his dad gave him when he was 10. He became an IT director, programmer, and author of books on various programming languages, Microsoft Office, web programming, and PCs. But Lowe never forgot his first love: electronics.

This article can be found in the category: