Java Reference
In-Depth Information
Save this as
ch8 _ question2.html
.
The key to this solution is getting a random number between
0
and the length of the
myImages
array, and writing a function to generate a random number would greatly help with that. So, you
write a function called
getRandomNumber()
:
function getRandomNumber(min, max) {
return Math.floor(Math.random() * max) + min;
}
It generates a random number within the range of
min
and
max
. The algorithm was copied from
Chapter 5.
Now you can use
getRandomNumber()
to generate a number for you, passing
0
as the min and the
length of the array as the max:
var random = getRandomNumber(0, myImages.length);
You then use the random number to get the image:
document.images[0].src = myImages[random];
Chapter 9
exercise 1 Question
Here's some HTML code that creates a table. Re‐create this table using only JavaScript and the core
DOM objects to generate the HTML. Test your code in all browsers available to you to make sure
it works in them. Hint: Comment each line as you write it to keep track of where you are in the tree
structure, and create a new variable for every element on the page (for example, not just one for each
of the TD cells but nine variables).
<table>
<tr>
<td>Car</td>
<td>Top Speed</td>
<td>Price</td>
</tr>
<tr>
<td>Chevrolet</td>
<td>120mph</td>
<td>$10,000</td>
</tr>
<tr>
<td>Pontiac</td>
<td>140mph</td>
<td>$20,000</td>
</tr>
</table>