HTML and CSS Reference
In-Depth Information
Generating Random Numbers
One of the most useful applications of JavaScript is to create dynamic pages that can
change in a random fashion. A commercial Web site might need to display banner
ads in a random order so that customers see a different ad each time they access the
page. To create these kinds of effects, you need a script that generates a random value.
JavaScript accomplishes this using the Math.random() method, which returns a ran-
dom value between 0 and 1. You can enlarge the range of possible random values using
the expression
lowest + size *Math.random()
where lowest is the lower boundary of the range and size is the size of the range. For
example, to generate a random number from 20 to 30, you could apply the following
20 + 10*Math.random();
In many cases, you want to limit a random number to integer values. To do so, you apply
the Math.floor() method to round the random values down to the next lowest integer,
as follows
Math.floor( lowest + size *Math.random())
where lowest is the lowest integer value and size is the number of integer values
greater than or equal to the lowest integer. Thus, to generate a random integer from 20
to 30, you would apply the following expression:
Math.floor(20 + 11*Math.random());
Note that this expression multiplies the random value by 11, not 10, because there are
11 integers in the range from 20 to 30. You could combine all of these operations in a
customized function that returns a random integer given a specified range and lower
boundary. The code for the function would be:
function randInt(lowest, size) {
return Math.floor(lowest + size*Math.random());
You could then use the randInt() function to generate a random integer from 1 to 10
using the following expression:
var randInteger = randInt(1, 10);
To create a random integer from a different range of values, you'd simply change the
values for the lowest and size parameters in the randInt() function.
Using Math Constants
Many functions require the use of mathematical constants, such as π and e . Rather than
entering the numeric values of these constants directly into code, you can reference the
built-in constants stored in the JavaScript Math object. The syntax to access one of these
mathematical constants is
where CONSTANT is the name of one of the mathematical constants supported by the
Math object, shown in Figure 11-21.
Search WWH ::

Custom Search