Main Page

Host objects

Even though these methods are defined by ECMA-262, the results are implementation-dependent because
you can calculate each value in many different ways. Consequently, the precision of the results may also
vary from one implementation to another.
The last method of the
object is
. This method returns a random number between the 0
and 1, not including 0 and 1. This is a favorite tool of Web sites that are trying to display random quotes
or random facts upon entry. You can use
to select numbers within a certain range by using the
following formula:
number = Math.floor(Math.random() * total_number_of_choices + first_possible_value)
method is used here because
always returns a decimal value, meaning that mul-
tiplying it by a number and adding another still yields a decimal value. Most of the time, you want to
select a random integer. Because of that, the
method is needed. So, if you wanted to select a
number between 1 and 10, the code looks like this:
var iNum = Math.floor(Math.random() * 10 + 1);
You see 10 possible values (1 through 10) with the first possible value being 1. If you want to select a
number between 2 and 10, then the code looks like this:
var iNum = Math.floor(Math.random() * 9 + 2);
There are only nine numbers when counting from 2 to 10, so the total number of choices is 9 with the
first possible value being 2. Many times, it’s just easier to use a function that handles the calculation of
the total number of choices and the first possible value:
function selectFrom(iFirstValue, iLastValue) {
var iChoices = iLastValue – iFirstValue + 1;
return Math.floor(Math.random() * iChoices + iFirstValue);
//select from between 2 and 10
var iNum = selectFrom(2, 10);
Using the function, it’s easy to select a random item from an
var aColors = [“red”, “green”, “blue”, “yellow”, “black”, “purple”, “brown”];
var sColor = aColors[selectFrom(0, aColors.length-1)];
Here, the second parameter to
is the length of the array minus 1, which (as you remem-
ber) is the last position in an array.
Host objects
Any object that is not native is considered to be a
host object
, which is defined as an object provided by
the host environment of an ECMAScript implementation. All BOM and DOM objects are considered to
be host objects and are discussed later in the book.
Object Basics
06_579088 ch03.qxd 3/28/05 11:36 AM Page 87

JavaScript EditorFree JavaScript Editor     Ajax Editor