HTML and CSS Reference
In-Depth Information
Subscripts are placed after the array name in square [ ] brackets, as shown in the
example in Table 11-7. A subscript must be any valid JavaScript variable or numeric literal
value. The first element in a JavaScript array always is element zero [0].
After the data elements are assigned to the array, the JavaScript code can retrieve or
use the data by referencing the array name with the subscript. As shown in Figure 11-9,
the data in an array is stored sequentially. For example, to reference the second element
(chapter11_1blackant.jpg), the JavaScript code uses the contents of randomImage[1].
To reference the third element in the array, the JavaScript code uses the contents of
randomImage[2].
items in array
random number
generated
null or empty value
because random number
will never be zero
0
1
2
3
4
N
Chapter11-1b_bee3.jpg
Chapter11-1blackant.jpg
Chapter11-1deer.jpg
Chapter11-1dragonfly1.jpg
Chapter11-1monarch.jpg
0
1
2
3
4
N
Array subscript values
Figure 11-9
The next step in updating the Hickory Oaks Forest Preserve Home page is to
create the user-defined function to display an image from an array using a random number
generator. With this function, the Web page will show a different image every time the
page is loaded. Table 11-8 shows the code for the creating the array object, generating the
random number, and assigning the new image to the image placeholder.
Table 11-8 Code for User-Defined Functions to Create a Randomly Displayed Image
Line
Code
23
var randomImage = new Array (“”, “chapter11-1b_bee3.jpg”,
“chapter11-1blackant.jpg”, “chapter11-1deer.jpg”,
”chapter11-1dragonfly1.jpg”, “chapter11-1gray_squirrel.jpg”,
”chapter11-1monarch.jpg”)
24
function rndimage() {
25
rndnumsize=randomImage.length-1
26
var randomnumber=Math.ceil(Math.random()*rndnumsize)
27
document.getElementById(“dailyImage”).src=randomImage[randomnumber]
28
}
Line 23 creates the array object, randomImage, with one null element and six image
filenames. The null element is created by an empty set of quotation marks (""). Line 24
declares the user-defined function, rndimage(). Line 25 determines the maximum value of
Search WWH ::




Custom Search