Java Reference
In-Depth Information
after the data items have been declared. In that case you will have to use the latter method of
defining the values of the array elements.
You'll also spot from the preceding example that you can store different data types in
the same array. JavaScript is very flexible as to what you can put in an array and where
you can put it.
an array
trY it out
In this example, you create an array to hold some names, and you use the second method described in
the preceding section to store these pieces of data in the array. You then display the data to the user.
Type this code and save it as ch2 _ example8.html :
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Chapter 2, Example 8</title>
</head>
<body>
<script>
var myArray = [];
myArray[0] = "Jeremy";
myArray[1] = "Paul";
myArray[2] = "John";
document.write("myArray[0] = " + myArray[0] + "<br/>");
document.write("myArray[2] = " + myArray[2] + "<br/>");
document.write("myArray[1] = " + myArray[1] + "<br/>");
myArray[1] = "Mike";
document.write("myArray[1] changed to " + myArray[1]);
</script>
</body>
</html>
If you load this into your web browser, you should see a web page that looks something like the one
shown in Figure 2-10.
The first task in the script block is to declare a variable and initialize it as an array:
var myArray = [];
Now that you have your array defined, you can store some data in it. Each time you store an item of
data with a new index, JavaScript automatically creates a new storage space for it. Remember that the
first element will be at myArray[0] .
Take each addition to the array in turn and see what's happening. Before you add anything, your array
is empty. Then you add an array element with the following line:
myArray[0] = "Jeremy";
Search WWH ::




Custom Search