Java Reference
In-Depth Information
Before going on to an example, note here that if, for example, you had defi ned your array called myArray
as holding three elements like this:
var myArray = new Array(3);
and then defi ned a value in the element with index 130 as follows:
myArray[130] = “Paul”;
JavaScript would not complain and would happily assume that you had changed your mind and
wanted an array that had (at least) 131 elements in it.
Try It Out An Array
In the following example, you'll create an array to hold some names. You'll use the second method
described in the preceding section to store these pieces of data in the array. You'll then display the data
to the user. Type the code and save it as ch2_examp8.htm.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script type=”text/javascript”>
var myArray = new Array();
myArray[0] = “Bob”;
myArray[1] = “Pete”;
myArray[2] = “Paul”;
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-11.
myArray[0] = Bob
myArray[2] = Paul
myArray[1] = Pete
myArray[1] changed to Mike
Figure 2-11
Search WWH ::




Custom Search