Học JavaScript qua ví dụ part 28 pps

7 199 0
Học JavaScript qua ví dụ part 28 pps

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

Thông tin tài liệu

ptg 9.5 The Math Object 241 9.5 The Math Object The Math object allows you to work with more advanced arithmetic calculations, such as square root, trigonometric functions, logarithms, and random numbers, than are pro- vided by the basic numeric operators. If you are doing simple calculations, you really won’t need it. Unlike other objects, you don’t have to create an instance of the Math object with the new keyword. It is a built-in object and has a number of properties (see Table 9.5) and methods (see Table 9.6). The Math object always starts with an uppercase M. EXPLANATION 1 The function called weekDay() is defined. 2 The variable now is assigned a number representing the day of the week, where 0 is Sunday. 3 A new Array object called names is created. It will contain seven elements. Each element will be assigned the name of the weekday (e.g., “Sunday”). 4 The value in now, a number between 0 and 6, will be used as an index in the names array. If now is 6, then the value of names[6], “Saturday”, will be returned. 5 A prototype method called DayOfWeek is assigned the name of the function week- Day. Now the Date object has a new method that will be inherited by all objects created from the Date() constructor. The capabilities of the Date object have been extended to provide a method that will return the name of the weekday. (See Chapter 8 for more on prototypes.) 6 A new Date object is created with the Date() constructor function. 7 The new prototype method is called, and returns the string value of today’s date, “Saturday” (see Figure 9.23). Figure 9.23 The day is converted to a string using a prototype. Table 9.5 Math Object Properties Property Value Description Math.E 2.718281828459045091 Euler’s constant, the base of natural logarithms Math.LN2 0.6931471805599452862 Natural log of 2 Math.LN10 2.302585092994045901 Natural log of 10 Continues From the Library of WoweBook.Com ptg 242 Chapter 9 • JavaScript Core Objects Math.LOG2E 1.442695040888963387 Log base-2 of E Math.Log10E 0.4342944819032518167 Log base-10 of E Math.PI 3.14592653589793116 Pi, ratio of the circumference of a circle to its diameter Math.SQRT1_2 0.7071067811865475727 1 divided by the square root of 2 Math.SQRT2 1.414213562373985145 Square root of 2 Table 9.6 Math Object Methods Method Functionality Math.abs(Number) Returns the absolute (unsigned) value of Number Math.acos(Number) Arc cosine of Number, returns result in radians Math.asin(Number) Arc sine of Number, returns results in radians Math.atan(Number) Arctangent of Number, returns results in radians Math.atan2(y,x) Arctangent of y/x; returns arctangent of the quotient of its arguments Math.ceil(Number) Rounds Number up to the next closest integer Math.cos(Number) Returns the cosine of Number in radians Math.exp(x)* Euler’s constant to some power Math.floor(Number) Rounds Number down to the next closest integer Math.log(Number) Returns the natural logarithm of Number (base E) Math.max(Number1, Number2) Returns larger value of Number1 and Number2 Math.min(Number1, Number2) Returns smaller value of Number1 and Number2 Math.pow(x, y) Returns the value of x to the power of y(x y ), where x is the base and y is the exponent Math.random() Generates pseudorandom number between 0.0 and 1.0 Math.round(Number) Rounds Number to the closest integer Math.sin(Number) Arc sine of Number in radians Math.sqrt(Number) Square root of Number Table 9.5 Math Object Properties (continued) Property Value Description From the Library of WoweBook.Com ptg 9.5 The Math Object 243 Square Root, Power of, and Pi. The Math object comes with a number of common mathematical constants (all uppercase), such as PI and natural log values, as well as meth- ods to find the square root of a number, the power of a number, and so on. Example 9.20 demonstrates how to use some of these properties; the output is shown in Figure 9.24. Math.tan(Number) Tangent of Number in radians Math.toString(Number) Converts Number to string * Returns the value of E x where E is Euler’s constant and x is the argument passed to it. Euler’s constant is approximately 2.7183. EXAMPLE 9.20 <html> <head><title>The Math Object</title></head> <body> <h2>Math object Methods sqrt(),pow()<br /> Math object Property PI </h2> <h3> <script type="text/javascript"> 1 var num=16; document.write("The square root of " +num+ " is "); document.write(Math.sqrt(num),".<br />"); 2 document.write("PI is "); 3 document.write(Math.PI); document.write(".<br />"+num+" raised to the 3rd power is " ); 4 document.write(Math.pow(num,3) + "."); </script> </h3> </body> </html> EXPLANATION 1 The number 16 will be manipulated by Math methods and constants. 2 The Math object’s sqrt() method returns the square root of number 16, which is 4. 3 The Math object’s PI constant produces the value of PI. 4 The Math object’s pow() methods raises and returns number 16 to the 3rd power, which is 4096 (see Figure 9.24). Table 9.6 Math Object Methods (continued) Method Functionality From the Library of WoweBook.Com ptg 244 Chapter 9 • JavaScript Core Objects 9.5.1 Rounding Up and Rounding Down There are three Math methods available for rounding numbers up or down. They are the ceil(), floor(), and round() methods (see Table 9.7 for examples). The differences among the methods might be confusing because all three methods truncate the numbers after the dec- imal point and return a whole number. If you recall, JavaScript also provides the parseInt() function, but this function truncates the number after the decimal point, without rounding either up or down. The ceil() Method. The ceil() method rounds a number up to the next largest whole number and then removes any numbers after the decimal point; thus, 5.02 becomes 6 because 6 is the next largest number, and –5.02 becomes –5 because –5 is larger than –6. The floor() Method. The floor() method rounds a number down to the next lowest whole number and then removes any numbers after the decimal point; thus, 5.02 now becomes 5, and –5.02 becomes –6. The round() Method. The round() method rounds up only if the decimal part of the number is .5 or greater. Otherwise, it rounds down to the nearest integer; thus, 5.5 is rounded up to 6, and 5.4 is rounded down to 5. Figure 9.24 The Math object, some properties and methods. Table 9.7 Rounding up and down Number ceil() floor() round() 2.55 3 2 3 2.30 3 2 2 –2.5 –2 –3 –2 –2.3 –2 –3 –2 From the Library of WoweBook.Com ptg 9.5 The Math Object 245 9.5.2 Generating Random Numbers Random numbers are frequently used in JavaScript programs to produce random images (such as banners streaming across a screen), random messages, or random numbers EXAMPLE 9.21 <html> <head><title>The Math Object</title></head> <body> <h2>Rounding Numbers</h2> <p> <h3> <script type="text/javascript"> 1 var num=16.3; document.write("<I>The number being manipulated is: ", num, "</I><br /><br />"); 2 document.write("The <I>Math.floor</I> method rounds down: " + Math.floor(num) + "<br />"); 3 document.write("The <I>Math.ceil</I> method rounds up: " + Math.ceil(num) +"<br />"); 4 document.write("The <I>Math.round</I> method rounds to\ the nearest integer: " + Math.round(num) + "<br />"); </script> </h3> </body> </html> EXPLANATION 1 The number 16.3 will be manipulated by the Math object’s methods. 2 The Math object’s floor() method rounds the number down to the next lowest whole number. 16.3 rounds down to 16. 3 The Math object’s ceil() method rounds a number up. 16.3 becomes 17. 4 The Math object’s round() methods round 16.3 up only if the decimal part of the number is 5 or higher (see Figure 9.25). Figure 9.25 Output from Example 9.21. From the Library of WoweBook.Com ptg 246 Chapter 9 • JavaScript Core Objects (such as for lotteries or card games). There are examples throughout this text where ran- dom numbers are used. The Math object’s random() method returns a random fractional number between 0 and 1 and is seeded with the computer’s system time. (The seed is the starting number for the algorithm that produces the random number.) The Math object’s floor() method truncates numbers after the decimal point and returns an integer. 9.5.3 Wrapper Objects (String, Number, Function, Boolean) A wrapper is an object bearing the same name as the primitive data type it represents. For each of the primitive data types (string, number, and Boolean), there is a String object, a Number object, and a Boolean object. These objects are called wrappers and EXAMPLE 9.22 <html> <head><title>Random Numbers</title></head> <body bgcolor="darkblue"> <p style="font-size:120%;color:white"> <script type="text/javascript"> 1 for(i=0; i < 10;i++){ // Generate random numbers between 0 and 1 2 document.write(Math.random(),"<br />"); } document.write("<br />"); // Generate random numbers between 0 and 10 3 for(i=0; i < 20; i++){ 4 document.write(Math.floor(Math.random() * 10 )+""); } </script> </p> </body> </html> EXPLANATION 1 The for loop is entered and will cause the body of the block to be executed 10 times, thus producing 10 fractional random numbers between 0 and 1. 2 The random() method of the Math object produces random numbers between 0 and 1. 3, 4 This for loop will cycle 20 times producing 20 random numbers between 0 and 10, achieved by multiplying the return value of the random number by 10 and then using the floor() method to round down the number to produce a whole number. This will produce 0 but never 10 (see Figure 9.26 on page 247). From the Library of WoweBook.Com ptg 9.5 The Math Object 247 provide properties and methods that can be defined for the object. For example, the String object has a number of methods that let you change the font color, size, and style of a string; and the Number object has methods that allow you to format a number to a specified number of significant digits. Whether you use the object or literal notation to create a string, number, or Boolean, JavaScript handles the internal conversion between the types. The real advantage to the wrapper object is its ability to apply and extend properties and methods to the object, which in turn, will affect the primitive. 9.5.4 The String Object We have used strings throughout this book. They were sent as arguments to the write() and writeln() methods, they have been assigned to variables, they have been concate- nated, and so on. As you might recall, a string is a sequence of characters enclosed in either double or single quotes. The String object (starting with JavaScript 1.1) is a core JavaScript object that allows you to treat strings as objects. The String object is also called a wrapper object because it wraps itself around a string primitive, allowing you to apply a number of properties and methods to it. You can create a String object implicitly by assigning a quoted string of text to a vari- able, called a string primitive (see “Primitive Data Types” on page 53 of Chapter 3, “The Building Blocks: Data Types, Literals, and Variables”), or by explicitly creating a String object with the new keyword and the String() object constructor method. Either way, the properties and methods of the String object can be applied to the new string variable. Figure 9.26 Producing random numbers (Example 9.22). From the Library of WoweBook.Com . Properties Property Value Description Math.E 2.71 8281 8284 59045091 Euler’s constant, the base of natural logarithms Math.LN2 0.69314718055994 5286 2 Natural log of 2 Math.LN10 2.302585092994045901. circle to its diameter Math.SQRT1_2 0.7071067811865475727 1 divided by the square root of 2 Math.SQRT2 1.414213562373985145 Square root of 2 Table 9.6 Math Object Methods Method Functionality Math.abs(Number). radians Math.sqrt(Number) Square root of Number Table 9.5 Math Object Properties (continued) Property Value Description From the Library of WoweBook.Com ptg 9.5 The Math Object 243 Square Root, Power

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

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan