JavaScript Arrays

Array handling in JavaScript is very similar to PHP, although the syntax is a little different. Nevertheless, given all you have already learned about arrays, this section should be relatively straightforward for you.

To create a new array, use the following syntax:

arrayname = new Array()

Or you can use the shorthand form, as follows:

arrayname = []

An associative array is one whose elements are referenced by name rather than by numeric offset. To create an associative array, define a block of elements within curly braces. For each element, place the key on the left and the contents on the right of a colon (:). Example 15-9 shows how you might create an associative array to hold the contents of the “balls” section of an online sports equipment retailer.

To verify that the array has been created and populated correctly, I have used another kind of for loop using the in keyword. This creates a new variable to use only within the array (ball in this example) and iterates through all elements of the array to the right of the in keyword (balls in this example). The loop acts on each element of balls, placing the key value into ball.

Using this key value stored in ball, you can also get the value of the current element of balls. The result of calling up the example script in a browser is as follows:

golf = Golf balls, 6
tennis = Tennis balls, 3
soccer = Soccer ball, 1
ping = Ping Pong balls, 1 doz

To get a specific element of an associative array, you can specify a key explicitly, in the following manner (in this case outputting the value “Soccer ball, 1”):

document.write(balls['soccer'])

To create a multidimensional array in JavaScript, just place arrays inside other arrays. For example, to create an array to hold the details of a two-dimensional checkerboard (8×8 squares), you could use the code in Example 15-10.

In this example, the lowercase letters represent black pieces and the uppercase white. A pair of nested for loops walk through the array and display its contents.

The outer loop contains two statements, so curly braces enclose them. The inner loop then processes each square in a row, outputting the character at location [j][k], followed by a space (to square up the printout). This loop contains a single statement, so curly braces are not required to enclose it. The <pre> and </pre> tags ensure that the output displays correctly, like this:

  o   o   o   o
o   o   o   o
  o   o   o   o


O   O   O   O
  O   O   O   O
O   O   O   O

You can also directly access any element within this array using square brackets, as follows:

document.write(checkerboard[7][2])

This statement outputs the uppercase letter O, the eighth element down and the third along—remember that array indexes start at 0, not 1.

Due to the power of arrays, JavaScript comes ready-made with a number of methods for manipulating them and their data. Here is a selection of the most useful ones.

You already saw how the push method can be used to insert a value into an array. The inverse method is pop. It deletes the most recently inserted element from an array and returns it. Example 15-13 shows an example of its use.

The three main statements of this script are shown in bold type. The script first creates an array called sports with three elements and then pushes a fourth element into the array. After that it pops that element back off. In the process, the various current values are displayed using document.write. The script outputs the following:

Start = Football,Tennis,Baseball
After Push = Football,Tennis,Baseball,Hockey
After Pop = Football,Tennis,Baseball
Removed = Hockey

The push and pop functions are useful in situations where you need to divert from some activity to do another, then return, as in Example 15-14.

The output from this example is:

Pushed 0
Pushed 1
Pushed 2

Popped 2
Popped 1
Popped 0

With the sort method, you can place all the elements of an array in alphabetical or other order, depending upon the parameters used. Example 15-16 shows four types of sort.

The first of the four example sections is the default sort method, alphabetical sort, while the second uses the default sort and then applies the reverse method to get a reverse alphabetical sort.

The third and fourth sections are a little more complicated, using a function to compare the relationships between a and b. The function doesn’t have a name, because it’s used just in the sort. You have already seen the function named function used to create an anonymous function; we used it to define a method in a class (the showUser method).

Here, function creates an anonymous function meeting the needs of the sort method. If the function returns a value less than zero, the sort assumes that a comes before b. If the function returns a value greater than zero, the sort assumes that b comes before a. If zero is returned the order of a and b is left unchanged as they are equal. The sort runs this function across all the values in the array to determine their order.

By manipulating the value returned (a - b in contrast to b - a), the third and fourth sections of Example 15-16 choose between an ascending numerical sort and a descending numerical sort.

And, believe it or not, this represents the end of your introduction to JavaScript. You should now have a core knowledge of three out of the four main technologies covered in this book. The next chapter will look at some advanced techniques used across these technologies, such as pattern matching and input validation.