The way you use the Mathobject in statements is the same way you use any JavaScript object: You create a reference beginning with the Mathobject’s name, a period, and the name of the pro
Trang 1The way you use the Mathobject in statements is the same way you use any JavaScript object: You create a reference beginning with the Mathobject’s name,
a period, and the name of the property or method you need:
Math.property | method([parameter] [,parameter])
Property references return the built-in values (things such as pi) Method refer-ences require one or more values to be sent as parameters of the method Every method returns a result
Properties
JavaScript Mathobject properties represent a number of valuable constant values in math Table 35-1 shows you those methods and their values as displayed
to 16 decimal places
Table 35-1 JavaScript Math Properties
Math.E 2.718281828459045091 Euler’s constant Math.LN2 0.6931471805599452862 Natural log of 2 Math.LN10 2.302585092994045901 Natural log of 10 Math.LOG2E 1.442695040888963387 Log base-2 of E Math.LOG10E 0.4342944819032518167 Log base-10 of E Math.PI 3.141592653589793116 π
Math.SQRT1_2 0.7071067811865475727 Square root of 0.5 Math.SQRT2 1.414213562373095145 Square root of 2
Because these property expressions return their constant values, you use them
in your regular arithmetic expressions For example, to obtain the circumference of
a circle whose diameter is in variable d, employ this statement:
circumference = d * Math.PI
Perhaps the most common mistakes scripters make with these properties are failing to capitalize the Mathobject name and observing the case-sensitivity of property names
Methods
Methods make up the balance of JavaScript Mathobject powers With the exception of the Math.random()method, all Mathobject methods take one or more values as parameters Typical trigonometric methods operate on the single values passed as parameters; others determine which of the numbers passed along are the highest or lowest of the group The Math.random()method takes
no parameters but returns a randomized, floating-point value between 0and 1
(note that the method does not work on Windows or Macintosh versions of
Math
Trang 2Navigator 2) Table 35-2 lists all the Mathobject methods with their syntax and
descriptions of the values they return
Table 35-2 Math Object Methods
Math.abs(val) Absolute value of val
Math.acos(val) Arc cosine (in radians) of val
Math.asin(val) Arc sine (in radians) of val
Math.atan(val) Arc tangent (in radians) of val
Math.atan2(val1, val2) Angle of polar coordinates x and y
Math.ceil(val) Next integer greater than or equal to val
Math.cos(val) Cosine of val
Math.exp(val) Euler’s constant to the power of val
Math.floor(val) Next integer less than or equal to val
Math.log(val) Natural logarithm (base e) of val
Math.max(val1, val2) The greater of val1 or val2
Math.min(val1, val2) The lesser of val1 or val2
Math.pow(val1, val2) Val1 to the val2 power
Math.random() Random number between 0 and 1
Math.round(val) N+1 when val >= N.5; otherwise N
Math.sin(val) Sine (in radians) of val
Math.sqrt(val) Square root of val
Math.tan(val) Tangent (in radians) of val
HTML is not exactly a graphic artist’s dream environment, so using trig functions
to obtain a series of values for HTML-generated charting is not a hot JavaScript
prospect Only with the advent of positionable elements have scripters been able to
apply their knowledge of using these functions to define fancy trajectories for flying
elements For scripters who are not trained in programming, math is often a major
stumbling block But as you’ve seen so far, you can accomplish a great deal with
JavaScript by using simple arithmetic and a little bit of logic — leaving the
heavy-duty math for those who love it
Creating random numbers
The Math.random()method returns a floating-point value between 0 and 1 If
you design a script to act like a card game, you need random integers between 1
and 52; for dice, the range is 1 to 6 per die To generate a random integer between
zero and any top value, use the following formula:
Math
Trang 3Math.floor(Math.random() * n)
Here, nis the top number To generate random numbers between a different range, use this formula:
Math.floor(Math.random() * n) + m
Here, mis the lowest possible integer value of the range and nequals the top number of the range For the dice game, the formula for each die is
newDieValue = Math.floor(Math.random() * 6) + 1
Math object shortcut
In Chapter 39, you see details about a JavaScript construction that enables you
to simplify the way you address multiple Mathobject properties and methods in statements The trick is to use the withstatement
In a nutshell, the withstatement tells JavaScript that the next group of state-ments (inside the braces) refers to a particular object In the case of the Math
object, the basic construction looks like this:
with (Math) {
//statements
}
For all intervening statements, you can omit the specific references to the Math
object Compare the long reference way of calculating the area of a circle (with a radius of six units)
result = Math.pow(6,2) * Math.PI
to the shortcut reference way:
with (Math) { result = pow(6,2) * PI }
Though the latter occupies more lines of code, the object references are shorter and more natural when reading the code For a longer series of calculations involving
Mathobject properties and methods, the withconstruction saves keystrokes and reduces the likelihood of a case-sensitive mistake with the object name in a reference You can also include other full-object references within the withconstruction; JavaScript attempts to attach the object name only to those references lacking an object name On the downside, the withconstruction is not particularly efficient
in JavaScript because it must perform a lot of internal tracking in order to work
Number Object
constructor toExponential() MAX_VALUE toFixed()
Number
Trang 4MIN_VALUE toLocaleString()
NEGATIVE_INFINITY toPrecision()
POSITIVE_INFINITY valueOf()
prototype
Syntax
Creating a number object:
var val = new Number(number)
Accessing number and Numberobject properties and methods:
number.property | method([parameters])
Number.property | method([parameters])
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓ ✓ ✓ ✓ ✓
About this object
The Numberobject is rarely used because (for the most part) JavaScript satisfies
day-to-day numeric needs with a plain number value But the Numberobject contains
some information and power of value to serious programmers
First on the docket are properties that define the ranges for numbers in the
language The largest number (in both Navigator and Internet Explorer) is 1.79E+308;
the smallest number is 2.22E-308 Any number larger than the maximum is POSITIVE_
INFINITY; any number smaller than the minimum is NEGATIVE_INFINITY Rarely
will you accidentally encounter these values
More to the point of a JavaScript object, however, is the prototypeproperty In
Chapter 34, you see how to add a method to a stringobject’s prototype such that
every newly created object contains that method The same goes for the Number
prototypeproperty If you have a need to add common functionality to every
number object, this is where to do it This prototype facility is unique to
full-fledged number objects and does not apply to plain number values For experienced
programmers who care about such matters, JavaScript number objects and values
are defined internally as IEEE double-precision 64-bit values
Properties
constructor
See string.constructor(Chapter 34)
MAX_VALUE
MIN_VALUE
numberObject.constructor
Trang 5POSITIVE_INFINITY
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓ ✓ ✓ ✓ ✓
The Number.MAX_VALUEand Number.MIN_VALUEproperties belong to the static
Numberobject They represent constants for the largest and smallest possible posi-tive numbers that JavaScript (and ECMAScript) can work with Their actual values are 1.7976931348623157 *, 10308, and 5 * 10- 324, respectively
A number that falls outside the range of allowable numbers is equal to the constant Number.POSITIVE_INFINITYor Number.NEGATIVE_INFINITY
Example on the CD-ROM
Related Items:NaN property; isNaN()global function
NaN
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓ ✓ ✓ ✓ ✓
The NaNproperty is a constant that JavaScript uses to report when a number-related function or method attempts to work on a value other than a number or the result is something other than a number You encounter the NaNvalue most commonly
as the result of the parseInt()and parseFloat()functions whenever a string undergoing conversion to a number lacks a numeral as the first character Use the
isNaN()global function to see if a value is an NaNvalue
Example
See the discussion of the isNaN()function in Chapter 42
Related Item:isNaN()global function
prototype
See String.prototype(Chapter 34)
On the
CD-ROM
Number.prototype
Trang 6number.toExponential(fractionDigits)
number.toFixed(fractionDigits)
number.toPrecision(precisionDigits)
Returns: String.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
A recent addition to the ECMA language — and thus to the JavaScript-enabled
browsers — are three Numberobject methods that let scripts control the formatting
of numbers for display as string text Each method has a unique purpose, but they
all return strings You should perform all math operations as unformatted number
objects because the values have the most precision Only after you are ready to
display the results should you use one of these methods to convert the number to
a string for display as body text or assignment to a text field
The toExponential()method forces a number to display in exponential
nota-tion, even if the number is in the range in which JavaScript normally uses standard
notation The parameter is an integer specifying how many digits to the right of the
decimal should be returned All digits to the right of the decimal are returned, even
if they are zero For example, if a variable contains the numeric value 345, applying
toExponential(3)to that value yields 3.450e+2, which is JavaScript’s exponential
notation for 3.45 × 102
Use the toFixed()method when you want to format a number with a specific
number of digits to the right of the decimal This is the method you use, for instance,
to display the results of a financial calculation in units and hundredths of units (for
example, dollars and cents) The parameter to the method is an integer indicating
the number of digits to be displayed to the right of the decimal If the number being
formatted has more numbers to the right of the decimal than the number of digits
specified by the parameter, the method rounds the rightmost visible digit — but
only with respect to the unrounded value of the next digit For example, the value
123.455fixed to two digits to the right of the decimal is rounded up to 123.46
But if the starting value is 123.4549, the method ignores the 9 and sees that the 4
to the right of the 5 should be rounded down; therefore, the result is 123.45 Do
not consider the toFixed()method to be an accurate rounder of numbers; however,
it does a satisfactory job in most cases
The final method is toPrecision(), which enables you to define how many total
digits (including digits to the left and right of the decimal) to display of a number In
other words, you define the precision of a number The following list demonstrates
the results of several parameter values signifying a variety of precisions:
var num = 123.45
num.toPrecision(1) // result = 1e+2
num.toPrecision(2) // result = 1.2e+2
num.toPrecision(3) // result = 123
numberObject.toExponential()
Trang 7num.toPrecision(4) // result = 123.5 num.toPrecision(5) // result = 123.45 num.toPrecision(6) // result = 123.450
Notice that the same kind of rounding can occur with toPrecision()as it does for toFixed()
Example on the CD-ROM
Related Item:Mathobject
number.toLocaleString()
Returns: String.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
According to the ECMA Edition 3 standard, browsers have some leeway in deter-mining exactly how the toLocaleString()method should return a string value that conforms with the language standard of the client system or browser IE5.5 appears to return the same value as the toFixed(2)method
Related Items:number.toFixed(), number.toString()methods
number.toString([radix])
Returns: String.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓ ✓ ✓ ✓ ✓
The number.toString()method returns a string value version of the current number The default radix parameter (10) converts the value to base-10 notation if the original number isn’t already of that type Or you can specify other number bases (for example, 2for binary, 16for hexadecimal) to convert the original number to the other base — as a string, not a number, for further calculation
Example on the CD-ROM
Related Item:toLocaleString()method
On the
CD-ROM
On the
CD-ROM
numberObject.toString()
Trang 8See string.valueOf()(Chapter 34)
Boolean Object
constructor toString()
prototype valueOf()
Syntax
Creating a Booleanobject:
var val = new Boolean(BooleanValue)
Accessing Booleanobject properties:
BooleanObject.property | method
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓ ✓ ✓ ✓ ✓
About this object
You work with Boolean values a lot in JavaScript — especially as the result of
conditional tests Just as string values benefit from association with string objects
and their properties and methods, so, too, do Boolean values receive aid from the
Booleanobject For example, when you display a Boolean value in a text box, the
“true”or “false”string is provided by the Booleanobject’s toString()method
so you don’t have to invoke it directly
The only time you need to even think about a Booleanobject is if you wish to
attach some property or method to Booleanobjects that you create with the new
Boolean()constructor Parameter values for the constructor include the string
versions of the values, numbers (0 for false; any other integer for true), and
expressions that evaluate to a Boolean value Any such new Booleanobject is
imbued with the new properties or methods you add to the prototypeproperty
of the core Booleanobject
For details about the properties and methods of the Booleanobject, see the
corresponding listings for the Stringobject in Chapter 34
BooleanObject
Trang 10The Date Object
Perhaps the most untapped power of JavaScript is its
date and time handling Scripters passed over the Date
object with good cause in the early days of JavaScript, because
in earlier versions of scriptable browsers, significant bugs and
platform-specific anomalies made date and time programming
hazardous without significant testing Even with the improved
bug situation, working with dates requires a working knowledge
of the world’s time zones and their relationships with the
standard reference point, known as Greenwich Mean Time
(GMT) or Coordinated Universal Time (abbreviated UTC)
Now that date- and time-handling has improved in the
latest browsers, I hope more scripters look into incorporating
these kinds of calculations into their pages In Chapter 54,
for example, I show you an application that lets your Web site
highlight the areas that have been updated since each visitor’s
last surf ride through your pages — an application that relies
heavily on date arithmetic and time zone conversion
Before getting to the JavaScript part of date discussions,
however, the chapter summarizes key facts about time zones
and their impact on scripting date and time on a browser If
you’re not sure what GMT and UTC mean, the following
section is for you
Time Zones and GMT
By international agreement, the world is divided into distinct
time zones that allow the inhabitants of each zone to say with
confidence that when the Sun appears directly overhead, it is
roughly noon, squarely in the middle of the day The current
time in the zone is what we set our clocks to — the local time
That’s fine when your entire existence and scope of life go
no further than the width of your own time zone But with
instant communication among all parts of the world, your
scope reaches well beyond local time Periodically you must
be aware of the local time in other zones After all, if you live
in New York, you don’t want to wake up someone in Los
Angeles before dawn with a phone call from your office
For the rest of this section, I speak of the Sun “moving” as
if Earth were the center of the solar system I do so for the
convenience of our daily perception of the Sun arcing
Note
In This Chapter
Working with date and time values in JavaScript Performing date calculations Validating date entry form fields