1. Trang chủ
  2. » Công Nghệ Thông Tin

JavaScript Bible, Gold Edition part 112 potx

10 208 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

958 Part IV ✦ JavaScript Core Language Reference The way you use the Math object in statements is the same way you use any JavaScript object: You create a reference beginning with the Math object’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 Math object 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 Property Value Description 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 Math object name and observing the case-sensitivity of property names. Methods Methods make up the balance of JavaScript Math object powers. With the exception of the Math.random() method, all Math object 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 0 and 1 (note that the method does not work on Windows or Macintosh versions of Math 959 Chapter 35 ✦ The Math, Number, and Boolean Objects Navigator 2). Table 35-2 lists all the Math object methods with their syntax and descriptions of the values they return. Table 35-2 Math Object Methods Method Syntax Returns 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 960 Part IV ✦ JavaScript Core Language Reference Math.floor(Math.random() * n) Here, n is the top number. To generate random numbers between a different range, use this formula: Math.floor(Math.random() * n) + m Here, m is the lowest possible integer value of the range and n equals 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 Math object properties and methods in statements. The trick is to use the with statement. In a nutshell, the with statement 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 Math object properties and methods, the with construction 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 with construction; JavaScript attempts to attach the object name only to those references lacking an object name. On the downside, the with construction is not particularly efficient in JavaScript because it must perform a lot of internal tracking in order to work. Number Object Properties Methods constructor toExponential() MAX_VALUE toFixed() Number 961 Chapter 35 ✦ The Math, Number, and Boolean Objects MIN_VALUE toLocaleString() NaN toString() NEGATIVE_INFINITY toPrecision() POSITIVE_INFINITY valueOf() prototype Syntax Creating a number object: var val = new Number(number) Accessing number and Number object 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 Number object is rarely used because (for the most part) JavaScript satisfies day-to-day numeric needs with a plain number value. But the Number object 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 prototype property. In Chapter 34, you see how to add a method to a string object’s prototype such that every newly created object contains that method. The same goes for the Number. prototype property. 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 962 Part IV ✦ JavaScript Core Language Reference NEGATIVE_INFINITY POSITIVE_INFINITY Value: Number Read-Only NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓ ✓✓✓ The Number.MAX_VALUE and Number.MIN_VALUE properties belong to the static Number object. 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 *, 10 308 , and 5 * 10 - 324 , respectively. A number that falls outside the range of allowable numbers is equal to the constant Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY. Example on the CD-ROM Related Items: NaN property; isNaN() global function. NaN Value: NaN Read-Only NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓✓ ✓ ✓✓✓ The NaN property 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 NaN value 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 NaN value. 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 963 Chapter 35 ✦ The Math, Number, and Boolean Objects Methods number.toExponential(fractionDigits) number.toFixed(fractionDigits) number.toPrecision(precisionDigits) Returns: String. NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ A recent addition to the ECMA language — and thus to the JavaScript-enabled browsers — are three Number object 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 × 10 2 . 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.455 fixed 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() 964 Part IV ✦ JavaScript Core Language Reference num.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: Math object. number.toLocaleString() Returns: String. NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓✓ 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, 2 for binary, 16 for 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() 965 Chapter 35 ✦ The Math, Number, and Boolean Objects number.valueOf() See string.valueOf() (Chapter 34). Boolean Object Properties Methods constructor toString() prototype valueOf() Syntax Creating a Boolean object: var val = new Boolean(BooleanValue) Accessing Boolean object 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 Boolean object. For example, when you display a Boolean value in a text box, the “true” or “false” string is provided by the Boolean object’s toString() method so you don’t have to invoke it directly. The only time you need to even think about a Boolean object is if you wish to attach some property or method to Boolean objects 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 Boolean object is imbued with the new properties or methods you add to the prototype property of the core Boolean object. For details about the properties and methods of the Boolean object, see the corresponding listings for the String object in Chapter 34. ✦✦✦ BooleanObject . 958 Part IV ✦ JavaScript Core Language Reference The way you use the Math object in statements is the same way you use any JavaScript object: You create a reference. construction; JavaScript attempts to attach the object name only to those references lacking an object name. On the downside, the with construction is not particularly efficient in JavaScript because. generate a random integer between zero and any top value, use the following formula: Math 960 Part IV ✦ JavaScript Core Language Reference Math.floor(Math.random() * n) Here, n is the top number.

Ngày đăng: 06/07/2014, 06:20

Xem thêm: JavaScript Bible, Gold Edition part 112 potx