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.

Numeric Arrays

To create a new array, use the following syntax:

arrayname = new Array()

Or you can use the shorthand form, as follows:

arrayname = []

Assigning element values

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";

But 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 16-8 shows a simple script that creates an array, loads it with some values, and then displays them.

Example 16-8. Creating, building, and printing an array
<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> ...

Get Learning PHP, MySQL, and JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.