Main Page

alert

var iMin = Math.min(3, 54, 32, 16);
alert(iMin); //outputs “3”
Out of the number 3, 54, 32, and 16,
max()
returns the number 54 whereas
min()
returns the number 3.
These methods are useful to avoid extra loops and
if
statements to determine the maximum value out
of a group of numbers.
Another method is
abs()
, which returns the absolute value of a number. The absolute value is the posi-
tive version of a negative number (positive numbers are their own absolute values).
var iNegOne = Math.abs(-1);
alert(iNegOne); //outputs “1”
var iPosOne = Math.abs(1);
alert(iPosOne); //outputs “1”
In this example,
abs(-1)
returns
1
and so does
abs(1)
.
The next group of methods has to do with rounding decimal values into integers. Three methods,
ceil()
,
floor()
, and
round()
, handle rounding in different ways.
?
The
ceil()
method represents the
ceiling
function, which always rounds numbers up to the
nearest value.
?
The
floor()
method represents the
floor
function, which always rounds numbers down to the
nearest value.
?
The
round()
method represents a standard round function, which rounds up if the number is
more than halfway to the next value (0.5 of the way there) and rounds down if not. This is the
way you were taught to round in elementary school.
To illustrate how each of these methods works, consider using the value 25.5:
alert(Math.ceil(25.5)); //outputs “26”
alert(Math.round(25.5)); //outputs “26”
alert(Math.floor(25.5)); //outputs “25”
For
ceil()
and
round()
, passing in 25.5 returns 26, whereas
floor()
returns 25. Be careful not to use
these methods interchangeably because you could end up with some unexpected results.
Another group of methods relates to the use of exponents. These methods include the following:
exp()
,
which raises
Math.E
to a given power;
log()
, which returns the natural logarithm of a particular num-
ber;
pow()
, which raises a given number to a given power; and
sqrt()
, which returns the square root of
a given number.
Essentially,
exp()
and
log()
reverse each other, whereas
exp()
raises
Math.E
to a specific power and
log()
determines what exponent of
Math.E
is needed to equal the given value. For example:
var iNum = Math.log(Math.exp(10));
alert(iNum);
85
Object Basics
06_579088 ch03.qxd 3/28/05 11:36 AM Page 85


JavaScript EditorFree JavaScript Editor     Ajax Editor


©

R7