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 = []
In PHP, you could add a new element to an array by simply assigning it without specifying the element offset, like this:
$arrayname[] = "Element 1"; $arrayname[] = "Element 2";
In JavaScript you use the push
method to achieve the same thing, like
this:
arrayname.push("Element 1") arrayname.push("Element 2")
This allows you to keep adding items to an array without having
to keep track of the number of items. When you need to know how many
elements are in an array, you can use the length
property, like this:
document.write(arrayname.length)
Alternatively, if you wish to keep track of the element locations yourself and place them in specific locations, you can use syntax such as this:
arrayname[0] = "Element 1" arrayname[1] = "Element 2"
Example 15-8 shows a simple script that creates an array, loads it with some values, and then displays them.
<script> numbers = [] numbers.push("One") numbers.push("Two") numbers.push("Three") for (j = 0 ; j < numbers.length ; ++j) document.write("Element " + j + " = " + numbers[j] + "<br />") </script>
The output from this script is:
Element 0 = One Element 1 = Two Element 2 = Three
You can also create an array together with some initial elements
using the Array
keyword, like
this:
numbers = Array("One", "Two", "Three")
There is nothing stopping you from adding more elements afterwards as well.
So now you have a couple of ways you can add items to an array, and one way of referencing them. JavaScript offers many more, which I’ll get to shortly—but first we’ll look at another type of array.
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.
<script> balls = {"golf": "Golf balls, 6", "tennis": "Tennis balls, 3", "soccer": "Soccer ball, 1", "ping": "Ping Pong balls, 1 doz"} for (ball in balls) document.write(ball + " = " + balls[ball] + "<br />") </script>
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.
<script> checkerboard = Array( Array(' ', 'o', ' ', 'o', ' ', 'o', ' ', 'o'), Array('o', ' ', 'o', ' ', 'o', ' ', 'o', ' '), Array(' ', 'o', ' ', 'o', ' ', 'o', ' ', 'o'), Array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '), Array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '), Array('O', ' ', 'O', ' ', 'O', ' ', 'O', ' '), Array(' ', 'O', ' ', 'O', ' ', 'O', ' ', 'O'), Array('O', ' ', 'O', ' ', 'O', ' ', 'O', ' ')) document.write("<pre>") for (j = 0 ; j < 8 ; ++j) { for (k = 0 ; k < 8 ; ++k) document.write(checkerboard[j][k] + " ") document.write("<br />") } document.write("</pre>") </script>
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.
The concat
method
concatenates two arrays, or a series of values with an array. For
example, the following code outputs
“Banana,Grape,Carrot,Cabbage”:
fruit = ["Banana", "Grape"] veg = ["Carrot", "Cabbage"] document.write(fruit.concat(veg))
You can specify multiple arrays as arguments, in which case
concat
adds all their elements in
the order that the arrays are specified.
Here’s another way to use concat
, This time plain values are
concatenated with the array pets
,
which outputs “Cat,Dog,Fish,Rabbit,Hamster”:
pets = ["Cat", "Dog", "Fish"] more_pets = pets.concat("Rabbit", "Hamster") document.write(more_pets)
The forEach
method in
JavaScript is another way of achieving functionality similar to the
PHP foreach
keyword, but
only for browsers other than Internet Explorer.
To use it, you pass it the name of a function, which will be called
for each element within the array. Example 15-11 shows how.
<script> pets = ["Cat", "Dog", "Rabbit", "Hamster"] pets.forEach(output) function output(element, index, array) { document.write("Element at index " + index + " has the value " + element + "<br />") } </script>
In this case, the function passed to forEach
is called output
. It takes three parameters: the
element
, its index
, and the array
. These can be used as required by your
function. In this example, just the element
and index
values are displayed using the
function document.write
.
Once an array has been populated, the method is called up like this:
pets.forEach(output)
The output from which is:
Element at index 0 has the value Cat Element at index 1 has the value Dog Element at index 2 has the value Rabbit Element at index 3 has the value Hamster
Of course, as often is its way, Microsoft chose not to support
the forEach
method, so the previous
example will work only on non–Internet Explorer browsers. Therefore,
until IE does support it, and to ensure cross-browser compatibility,
you should use a statement such as the following instead of pets.forEach(output)
:
for (j = 0 ; j < pets.length ; ++j) output(pets[j], j)
With the join
method, you can
convert all the values in an array to strings and then join them
together into one large string, placing an optional separator between
them. Example 15-12 shows three ways of
using this method.
<script> pets = ["Cat", "Dog", "Rabbit", "Hamster"] document.write(pets.join() + "<br />") document.write(pets.join(' ') + "<br />") document.write(pets.join(' : ') + "<br />") </script>
Without a parameter, join
uses a comma to separate the elements; otherwise, the string passed to
join
is inserted between each
element. The output of Example 15-12 looks
like this:
Cat,Dog,Rabbit,Hamster Cat Dog Rabbit Hamster Cat : Dog : Rabbit : Hamster
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.
<script> sports = ["Football", "Tennis", "Baseball"] document.write("Start = " + sports + "<br />") sports.push("Hockey") document.write("After Push = " + sports + "<br />") removed = sports.pop() document.write("After Pop = " + sports + "<br />") document.write("Removed = " + removed + "<br />") </script>
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 push
es a fourth element into the array.
After that it pop
s 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.
<script> numbers = [] for (j=0 ; j<3 ; ++j) { numbers.push(j); document.write("Pushed " + j + "<br />") } // Perform some other activity here document.write("<br />") document.write("Popped " + numbers.pop() + "<br />") document.write("Popped " + numbers.pop() + "<br />") document.write("Popped " + numbers.pop() + "<br />") </script>
The output from this example is:
Pushed 0 Pushed 1 Pushed 2 Popped 2 Popped 1 Popped 0
The reverse
method simply
reverses the order of all elements in an array. Example 15-15 shows this in action.
<script> sports = ["Football", "Tennis", "Baseball", "Hockey"] sports.reverse() document.write(sports) </script>
The original array is modified and the output from this script is:
Hockey,Baseball,Tennis,Football
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.
<script> // Alphabetical sort sports = ["Football", "Tennis", "Baseball", "Hockey"] sports.sort() document.write(sports + "<br />") // Reverse alphabetical sort sports = ["Football", "Tennis", "Baseball", "Hockey"] sports.sort().reverse() document.write(sports + "<br />") // Ascending numerical sort numbers = [7, 23, 6, 74] numbers.sort(function(a,b){return a - b}) document.write(numbers + "<br />") // Descending numerical sort numbers = [7, 23, 6, 74] numbers.sort(function(a,b){return b - a}) document.write(numbers + "<br />") </script>
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.