Cover by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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

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.

Example 15-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>

The ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required