HTML and CSS Reference
In-Depth Information
(such as for lotteries or card games). There are examples throughout this text where ran-
dom numbers are used.
The
Math
object's
random()
method returns a random fractional number between 0
and 1 and is seeded with the computer's system time. (The seed is the starting number
for the algorithm that produces the random number.) The
Math
object's
floor()
method
truncates numbers after the decimal point and returns an integer.
EXAMPLE
9.22
<html>
<head><title>Random Numbers</title></head>
<body bgcolor="darkblue">
<p style="font-size:120%;color:white">
<script type="text/javascript">
1
for(i=0; i < 10;i++){
// Generate random numbers between 0 and 1
2
document.write(
Math.random()
,"<br />");
}
document.write("<br />");
// Generate random numbers between 0 and 10
3
for(i=0; i < 20; i++){
4
document.write(
Math.floor(Math.random() * 10
)+"");
}
</script>
</p>
</body>
</html>
EXPLANATION
1
The
for
loop is entered and will cause the body of the block to be executed 10
times, thus producing 10 fractional random numbers between 0 and 1.
2
The
random()
method of the
Math
object produces random numbers between 0
and 1.
3, 4
This
for
loop will cycle 20 times producing 20 random numbers between 0 and
10, achieved by multiplying the return value of the random number by 10 and
then using the
floor()
method to round down the number to produce a whole
number. This will produce 0 but never 10 (see Figure 9.26 on page 247).
A wrapper is an object bearing the same name as the primitive data type it represents.
For each of the primitive data types (string, number, and Boolean), there is a
String
object, a
Number
object, and a
Boolean
object. These objects are called
wrappers
and