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

Học JavaScript qua ví dụ part 30 pdf

12 263 0

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 12
Dung lượng 1,07 MB

Nội dung

ptg 9.5 The Math Object 259 9.5.5 The Number Object Now that we’ve travelled this far in JavaScript, have you wondered how to format a float- ing-point number when you display it, as you can with the printf function in C or Perl? Well, the Number object, like the String object, gives you properties and methods to handle and customize numeric data. The Number object is a wrapper for the primitive numeric values (see Chapter 2, “Script Setup”), which means you can use a primitive number type document.write("The search() method found \"dad\" at position "+ index +"<br />"); 4 var mysubstr=straddr.substr(index,3); document.write("After replacing \"dad\" with \"POP\" <br />"); 5 document.write(straddr.replace(mysubstr,"POP")+"<br />"); </script> </small> </font> </body> </html> EXPLANATION 1 An e-mail address is assigned to the string variable straddr. 2 The replace() method takes two arguments, the search string and the replacement string. If the substring Daniel is found, it is replaced with Jake. 3 The search() method takes a substring as its argument and returns the first posi- tion where a substring is found in a string. In this example the substring dad is searched for in the string DanielSavage@dadserver.org and is found at position 13. 4 The substr() method returns the substring found at position 13, 3 in the string, DanielSavage@dadserver.org: dad. 5 The substring dad is replaced with POP in the string (see Figure 9.35). Figure 9.35 The search() and replace() String methods: Output from Example 9.30. EXAMPLE 9.30 (CONTINUED) From the Library of WoweBook.Com ptg 260 Chapter 9 • JavaScript Core Objects or an object number type and JavaScript manages the conversion back and forth as neces- sary. The Number object was introduced in JavaScript 1.1. The Number() constructor takes a numeric value as its argument. If used as a func- tion, without the new operator, the argument is converted to a primitive numeric value, and that number is returned; if it fails, NaN is returned. The Number object has a number of properties and methods, as listed in Tables 9.11 and 9.12. FORMAT var number = new Number(numeric value); //Object var number = numeric value; // Primitive data type EXAMPLE var n = new Number(65.7); var n = 65.7; Table 9.11 The Number Object’s Properties Property What It Describes MAX_VALUE The largest representable number, 1.7976931348623157e+308 MIN_VALUE The smallest representable number, 5e–324 NaN Not-a-number value NEGATIVE_INFINITY Negative infinite value; returned on overflow POSITIVE_INFINITY Infinite value; returned on overflow prototype Used to customize the Number object by adding new properties and methods Table 9.12 The Number Object’s Methods Method What It Does toString() Converts a number to a string using a specified base (radix) toLocaleString() Converts a number to a string using local number conventions toFixed() Converts a number to a string with a specified number of places after the decimal point toExponential() Converts a number to a string using exponential notation and a specified number of places after the decimal point toPrecision() Converts a number to a string in either exponential or fixed notation containing the specified number of places after the decimal point From the Library of WoweBook.Com ptg 9.5 The Math Object 261 Using Number Constants and Different Bases. The constants MAX_VALUE, MIN_VALUE, NEGATIVE_INFINITY, POSITIVE_INFINITY, and NaN are properties of the Number() function, but are not used with instances of the Number object; thus, var huge = Number.MAX_VALUE is valid, but huge.MAX_VALUE is not. NaN is a special value that is returned when some mathematical operation results in a value that is not a number. The methods provided to the Number object manipulate instances of number objects. For example, to convert numbers to strings representing different bases, the toString() method manipulates a number, either primitive or object. See Example 9.31. EXAMPLE 9.31 <html> <head><title>Number Contants</title></head> <body bgcolor="orange"><font color="black" size="+1"> <h2>Constants</h2> <script type="text/javascript"> 1 var largest = Number.MAX_VALUE; 2 var smallest = Number.MIN_VALUE; 3 var num1 = 20; // A primitive numeric value 4 var num2 = new Number(13); // Creating a Number object document.write("<b>The largest number is " + largest + "<br />"); document.write("The smallest number is "+ smallest + "<br />"); 5 document.write("The number as a string (base 2): "+ num1.toString(2)); 6 document.write("<br />The number as a string (base 8): "+ num2.toString(8)); 7 document.write("<br />The square root of -25 is: "+ Math.sqrt(-25) + "<br />"); </script> </body> </html> EXPLANATION 1 The constant MAX_VALUE is a property of the Number() function. This constant cannot be used with an instance of a Number object. 2 The constant MIN_VALUE is a property of the Number() function. 3 A number is assigned to the variable called num1. 4 A new Number object is created with the Number() constructor and assigned to num2. It is easier to use the literal notation: num2 = 13. 5 The number is converted to a string represented in binary, base 2. 6 The number is converted to a string represented in octal, base 8. 7 The square root of a negative number is illegal. JavaScript returns NaN, not a number, when this calculation is attempted (see Figure 9.36). From the Library of WoweBook.Com ptg 262 Chapter 9 • JavaScript Core Objects Formatting Numbers. To convert floating-point numbers to a string with a speci- fied number of significant digits, JavaScript provides the toFixed() and toExponential() methods. You can apply these methods to a numeric variable whether it is created as a numeric literal or as an object. Figure 9.36 Constants, number conversion, and NaN: Output from Example 9.31. EXAMPLE 9.32 <html> <head><title>Number Object</title></head> <body bgcolor="orange"> <font color="black" size="+1"> <h2>Formatting Numbers</h2> <script type="text/javascript"> 1 var n = new Number(22.425456); // var n = 22.425456; 2 document.write("<b>The unformatted number is " + n + "<br />"); 3 document.write("The formatted number is "+ n.toFixed(2) + "<br />"); 4 document.write("The formatted number is "+ n.toFixed(3) + "</b><br />"); </script> </font> </body> </html> EXPLANATION 1 A new Number object is created and assigned to the variable n. It is a wrapper for the primitive number. 2 The value of the number is displayed as a large floating-point number, 22.425456. 3 The Number object’s toFixed() method gets an argument of 2. This fixes the deci- mal point two places to the right and rounds up if necessary. The new value is 22.43. 4 This time the toFixed() method will format the number with three numbers to the right of the decimal point (see Figure 9.37). From the Library of WoweBook.Com ptg 9.5 The Math Object 263 9.5.6 The Boolean Object The Boolean object was included in JavaScript 1.1. It is used to convert a non-Boolean value to a Boolean value, either true or false. There is one property, the prototype prop- erty, and one method, the toString() method, which converts a Boolean value to a string; thus, true is converted to “true” and false is converted to “false”. Figure 9.37 Using the toFixed() Number method: Output from Example 9.32. FORMAT var object = new Boolean(value); EXAMPLE var b1 = new Boolean(5); var b2 = new Boolean(null); EXAMPLE 9.33 <html> <head><title>Boolean Object</title></head> <body bgcolor=aqua> <font face="arial" size="+1"><b> The Boolean Object<br /> <small> <script type="text/javascript"> 1 var bool1= new Boolean( 0); var bool2 = new Boolean(1); var bool3 = new Boolean(""); var bool4 = new Boolean(null); var bool5 = new Boolean(NaN); 2 document.write("The value 0 is boolean " + bool1 + "<br>"); document.write("The value 1 is boolean " + bool2 + "<br>"); document.write("The value of the empty string is boolean " + bool3 + "<br />"); document.write("The value of null is boolean " + bool4 + "<br />"); Continues From the Library of WoweBook.Com ptg 264 Chapter 9 • JavaScript Core Objects 9.5.7 The Function Object The Function object lets you define a function as an object. It allows a string to be defined at runtime and then compiled as a function. You can use the Function() con- structor to create a variable that contains the function. Because the function has no name, it is often called an anonymous function and its arguments are passed as comma- separated strings. The last argument is the body of statements that will be executed when the function is called. If the Function() constructor does not require arguments, then the body of statements is treated as a string, and will be passed to the Function() constructor to define what the function is to do. Because functions are objects, they also have properties (see Table 9.13) and methods (see Table 9.14). Function objects are evaluated each time they are used, causing them to be slower in execution than normal JavaScript functions. document.write("The value of NaN is boolean " + bool5 + "<br />"); </script> </small> </font> </body> </html> EXPLANATION 1 The argument passed to the Boolean object constructor is the initial value of the object, either true or false. If the initial value is 0, the empty string “”, NaN, or null, the result is false; otherwise, the result is true. 2 The Boolean object’s values are displayed as either true or false (see Figure 9.38). Figure 9.38 True or False? Output from Example 9.33. Table 9.13 Properties of the Function Object Property What It Does length Returns the number of arguments that are expected to be passed (read only). prototype Allows the object to be customized by adding new properties and methods. EXAMPLE 9.33 (CONTINUED) From the Library of WoweBook.Com ptg 9.5 The Math Object 265 Table 9.14 Methods of the Function Object Property What It Does apply() Allows you to apply a method from one function to another. call() Allows you to call a method from another object. FORMAT var nameOfFunction = new Function (arguments, statements_as_string: } EXAMPLE F UNCTION DEFINITION var addemUp = new Function ( "a", "b", "return a + b;" ); EXAMPLE F UNCTION CALL document.write(addemUp(10, 5)); EXAMPLE 9.34 <html> <head><title>Function Object</title></head> <body bgcolor=lightgreen> <font face="arial" size="+1"> <center> Anonymous Functions and the Function Constructor<p> <script type="text/javascript"> 1 var sum = new Function("a","b", "return a + b; "); 2 window.onload = new Function ( "document.bgColor='yellow';"); 3 document.write( "The sum is " + sum(5,10)+ "<br />"); document.write( "The background color is yellow<br />"); </script> </font> </body> </html> EXPLANATION 1 A variable called sum is a Function object, created by the Function() constructor. It has two arguments, “a” and “b”. The function statements are the last string in the list. These statements will be executed when the function is called. 2 This Function() constructor only has one argument, the statement that will be ex- ecuted when the function is called. Because the function is assigned to the onload event method for the window object, it will be invoked when the window has fin- ished loading and cause the background color to be yellow. 3 The sum function is called with two arguments (see Figure 9.39). From the Library of WoweBook.Com ptg 266 Chapter 9 • JavaScript Core Objects 9.5.8 The with Keyword Revisited In Chapter 8, we used the with keyword with user-defined objects to make it easier to manipulate the object properties. Recall that any time you reference the object within the block following the keyword, you can use properties and methods without the object name. This saves a lot of typing and reduces the chances of spelling errors, especially when the properties have long names. The String object is used in the following example to demonstrate how with is used (see Figure 9.40). Figure 9.39 Output from Example 9.34. EXAMPLE 9.35 <html> <head><title>The with Keyword</title></head> <body> <h2>Using the <em>with</em> keyword</h2> <p> <h3> <script type="text/javascript"> var yourname=prompt("What is your name? ",""); // Create a string object 1 with(yourname){ document.write("Welcome " + yourname + " to our planet!!<br />"); 2 document.write("Your name is " + length + " characters in length.<br />"); 3 document.write("Your name in uppercase: " + toUpperCase() + ".<br />"); 4 document.write("Your name in lowercase: " + toLowerCase() + ".<br />"); } </script> </h3> </body> </html> EXPLANATION 1 The with keyword allows the methods of an object (in this example a string ob- ject) to be called without the object’s name and a dot. From the Library of WoweBook.Com ptg 9.6 What You Should Know 267 9.6 What You Should Know In the last chapter you learned how to create and manipulate your own objects, and in this chapter we concentrated on the built-in core objects of JavaScript and what proper- ties and methods are provided for these objects. You learned about the Array object so that later you can create arrays of images and links, and so on. You learned how to manipulate time and dates and how to manage strings and numbers. All of these objects are vital to working with JavaScript as they are at the heart of all JavaScript programs. At this time you should know: 1. What JavaScript’s core types are. 2. How to create an Array object with the new constructor. 3. How to find the size of an array. 4. How to create a literal array. 5. How to populate an array. 6. How to loop through an array. 7. How to create a two-dimensional array. 8. How to add and remove elements from an array. 9. The difference between slicing and splicing an array. 10. Five ways to instantiate a date object. 11. How JavaScript stores dates. 12. How to calculate the difference between two dates. 13. How to get the current year and month. 14. How to customize the Date object. 2 The property length of the string object called yourname is printed. Because the object is enclosed within a block following the with keyword, the name of the ob- ject is omitted. 3 The toUpperCase() method caused the str object’s character to be capitalized. 4 The toLowerCase() method caused the string to be lowercased. Figure 9.40 The with keyword and strings. EXPLANATION From the Library of WoweBook.Com ptg 268 Chapter 9 • JavaScript Core Objects 15. How to create a Math object. 16. How to use the properties of the Math object. 17. How to randomly select an array element. 18. How to control the number of decimal places in a number. 19. How to define a wrapper object. 20. How to find a character in a string. 21. How to find a substring in a string. 22. The meaning of NaN. 23. How to convert a number to a string. 24. How to get the square root of a number. From the Library of WoweBook.Com [...]... 270 Chapter 9 • JavaScript Core Objects 10 Create a string prototype that can be used to create italic, Verdana font, point size 26 text 11 Calculate the circumference of a circle using the Math object 12 Create a two-dimensional array consisting of numbers representing costs After creating the array, print out the values with a sales tax of 9 percent added to each cost 13 Write a JavaScript program... PV = PMT * ( 1 – (1 + IR )–NP) / IR PV is the present value of the loan; PMT is the regular monthly payment of the loan; IR is the loan’s interest rate; NP is the number of payments remaining Write a JavaScript statement to represent this formula 7 Using the formula to calculate the loan balance from the last exercise, write a function that will calculate the principal balance left on a loan where... Exercises You Should Know 269 E x e r c i ses 1 Create an array of five animals Use a for loop to display the values stored there Now add two more animals to the end of the array and sort the array (Use JavaScript s built-in array methods.) Display the sorted array 2 Create an associative array called colors Each element of the array is a string representing the color, for example, red or blue Use the . methods: Output from Example 9 .30. EXAMPLE 9 .30 (CONTINUED) From the Library of WoweBook.Com ptg 260 Chapter 9 • JavaScript Core Objects or an object number type and JavaScript manages the conversion. square root of a negative number is illegal. JavaScript returns NaN, not a number, when this calculation is attempted (see Figure 9.36). From the Library of WoweBook.Com ptg 262 Chapter 9 • JavaScript. of these objects are vital to working with JavaScript as they are at the heart of all JavaScript programs. At this time you should know: 1. What JavaScript s core types are. 2. How to create

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

TỪ KHÓA LIÊN QUAN