"JavaScript Advanced Program Design" Reading notes---monomer built-in objects

Source: Internet
Author: User
Tags decode all rounds alphanumeric characters

Global Object
The global (Global) object can be said to be the most special object in ECMAScript, because no matter what angle you look at it, this object is not there. The global object in ECMAScript is defined in a sense as the ultimate "backstop object". In other words, properties and methods that do not belong to any other object are ultimately its properties and methods. In fact, there are no global variables or global functions; All properties and functions defined in global scope are properties of global objects. The functions described earlier in this book, such as isNaN (), Isfinite (), parseint (), and parsefloat (), are all actually methods of the global object. In addition, the Global object contains several other methods.


1. URI Encoding method
the encodeURI () and encodeURIComponent () methods of the Global object can encode URIs(Uniform Resource Identifiers, Universal Resource Identifiers) , To send to the browser. A valid URI cannot contain certain characters, such as spaces. and these two URI encoding methods can encode the URI, they replace all invalid characters with special UTF-8 encoding, so that the browser can accept and understand.
where encodeURI () is used primarily for the entire URI (for example, Http://www.wrox.com/illegal value.htm), and Encode-uricomponent () is used primarily for a segment of the URI (for example, the preceding URI Illegal value.htm) in the code. The main difference is thatencodeURI () does not encode special characters that are themselves URIs, such as colons, forward slashes, question marks, and well sizes, while encodeuricomponent () encodes any non-standard characters it discovers . Take a look at the following example.

var uri = "Http://www.wrox.com/illegal Value.htm#start";
"Http://www.wrox.com/illegal%20value.htm#start"
Alert (encodeURI (URI));
"Http%3a%2f%2fwww.wrox.com%2fillegal%20value.htm%23start"
Alert (encodeURIComponent (URI));

The result of using encodeURI () encoding is that characters other than spaces are left intact, and only spaces are replaced with%20. The encodeURIComponent () method replaces all non-alphanumeric characters with the corresponding encoding. This is also the reason why you can use encodeURI () for the entire URI and only use encodeURIComponent () for strings appended to the existing URI.

Note: In general, we use the encodeURIComponent () method more often than encodeURI (), because in practice it is more common to encode query string parameters rather than base URIs.

The two methods corresponding to the encodeURI () and encodeURIComponent () methods are decodeURI () and decodeURIComponent () respectively. where decodeURI () can only decode characters that are replaced with encodeURI (). For example, it can replace%20 with a single space, but does not do anything with%23 because%23 represents the well font size (#), and the well font size is not replaced with encodeURI (). Similarly,decodeuricomponent () can decode all characters encoded using encodeuricomponent (), that is, it can decode the encoding of any special character. take a look at the following example:

var uri = "Http%3a%2f%2fwww.wrox.com%2fillegal%20value.htm%23start";
Http%3a%2f%2fwww.wrox.com%2fillegal Value.htm%23start
Alert (decodeURI (URI));
Http://www.wrox.com/illegal Value.htm#start
Alert (decodeURIComponent (URI));

Here, the variable URI contains a string encoded by encodeURIComponent (). In the result of the first call to the decodeURI () output, only%20 is replaced with a space. In the result of the second call to the decodeURIComponent () output, the encoding of all special characters is replaced with the original character, and an escaped string is obtained (but the string is not a valid URI).

2. Eval () method
Now, let's introduce the last one-probably the most powerful method in the entire ECMAScript language: eval (). The eval ()   method is like a complete ECMAScript parser that accepts only one parameter, the ECMAScript (or JavaScript) string to execute. Look at the following example:
eval ("Alert (' Hi ')");
The function of this line of code is equivalent to this line of code:
Alert ("HI");
When the parser discovers that the eval () method is called in the code, it parses the passed-in parameter as the actual ECMAScript statement, and then inserts the execution result into the original location. Code executed through eval () is considered part of the execution environment that contains the call, so the code being executed has the same scope chain as the execution environment. This means that code executed through eval () can reference a variable defined in the containing environment, for example:
var msg = "Hello World";
  Eval ("Alert (msg)"); The "Hello World"
shows that the variable MSG is defined outside the environment called by Eval (), but the alert () in which it is invoked can still display "Hello world". This is because the second line of code above is eventually replaced with a single line of real code. Similarly, we can also define a function in the eval () call, and then reference the function in the external code of the call:
Eval ("function Sayhi () {alert (' Hi ');}");
Sayhi ();
Obviously, the function sayhi () is defined internally in eval (). However, because the call to Eval () will eventually be replaced with the actual code that defines the function, you can call Sayhi () on the next line. The same is true for variables:

Eval ("var msg = ' Hello World ';");
Alert (msg); "Hello World"
Any variables or functions created in eval () are not promoted because they are included in a string when parsing the code, and they are only created when Eval () is executed.
In strict mode, no variables or functions created in eval () are accessed externally, so the previous two examples will cause an error. Similarly, in strict mode, assigning a value to Eval can also result in an error:
"Use strict";
eval = "HI"; Causes error

Note: The ability to interpret code strings is very powerful, but also very dangerous. Therefore, you must be extremely cautious when using eval (), especially if you are using it to perform user input data. Otherwise, malicious users may enter code that threatens the security of your site or application (known as code injection).

3. Properties of the Global object
The Global object also contains some properties, some of which have already been described earlier in this book. For example, special values undefined, NaN, and infinity are all properties of the global object. In addition, constructors for all native reference types, such as object and function, are also properties of the global object. The following table lists all the properties of the global object.

ECMAScript 5 explicitly prohibits assigning values to undefined, NaN, and infinity, which can cause errors even in non-strict mode.


4. Window Object
ECMAScript Although it does not indicate how to access the global object directly, the Web browser implements the global object as part of the Window object. Therefore, all variables and functions declared in the global scope become properties of the Window object. Take a look at the following example.
var color = "Red";
function Saycolor () {
alert (Window.color);
}
Window.saycolor (); "Red"

This defines a global variable named color and a global function named Saycolor (). Inside Saycolor (), we access the color variable through Window.color to show that the global variable is a property of the Window object. Then, using Window.saycolor () to invoke the function directly through the window object, the result is displayed in the Warning box.

Note: The Window object in JavaScript takes on many other tasks besides playing the role of the global object specified by ECMAScript. The 8th Chapter describes the window object in detail when discussing the browser object model.

Another way to get a global object is to use the following code:
var global = function () {
return this;
}();
The code above creates an immediately called function expression that returns the value of this. As mentioned earlier, this value is equal to the global object in cases where the function is not explicitly specified by the This value (either by adding the function as an object or by calling call () or apply ()). And, like this, it is possible to get the global object by simply returning this, in any execution environment. The 7th chapter discusses function expressions in depth.

Math Object
ECMAScript also provides a common place for saving mathematical formulas and information, the Math object. The Math object provides much faster execution than the computational capabilities that we write directly in JavaScript. The Math object also provides properties and methods that assist in completing these calculations.
1. Properties of the Math object
The Math object contains properties that are mostly special values that may be used in mathematical calculations. These properties are listed in the following table.

Although it is beyond the scope of this book to discuss the meanings and uses of these values, you can use them at any time.
2. Min () and Max () methods
The Math object also contains many methods for assisting in simple and complex mathematical calculations.
where the Min () and Max () methods are used to determine the minimum and maximum values in a set of values. Both methods can receive any number of numeric parameters, as shown in the following example.

var max = Math.max (3, 54, 32, 16);
Alert (max); 54
var min = math.min (3, 54, 32, 16);
Alert (min); 3

The

Returns 54 for 3, 54, 32, and 16,math.max (), and Math.min () returns 3. These two methods are often used to avoid redundant loops and to determine the maximum of a set of numbers in an if statement.
to find the largest or smallest value in the array, you can use the Apply () method as follows.
var values = [1, 2, 3, 4, 5, 6, 7, 8];
var max = Math.max.apply (Math, values); The key to the
technique is to use the Math object as the first parameter of apply () to set the this value correctly. Then, you can use any array as the second parameter.
3. Rounding Method
describes several methods for rounding decimal values to integers: Math.ceil (), Math.floor (), and Math.Round ().
These three methods follow the following rounding rules, respectively:
? Math.ceil () performs an upward rounding, that is, it always rounds the value up to the nearest integer;
? Math.floor () Performs a downward rounding, that is, it always rounds the value down to the nearest integer;
? Math.Round () performs a standard rounding, that is, it always rounds a number to the nearest integer (which is also the rounding rule we learned in math Class).
The following are examples of using these methods:
Alert (Math.ceil (25.9)),//26
Alert (Math.ceil (25.5)),//26
Alert (Math.ceil (25.1)),//26
Alert (Math.Round (25.9)),//26
Alert (Math.Round (25.5)),//26
Alert (Math.Round (25.1)),//25
Alert ( Math.floor (25.9));
Alert (Math.floor (25.5));//25
Alert (Math.floor (25.1));//25

For all values between 25 and 26 (not including 26), Math.ceil () always returns 26 because it performs rounding up. The Math.Round () method returns 26 only if the value is greater than or equal to 25.5, or 25. Finally, Math.floor () returns 25 for all values between 25 and 26 (not including 26).
4. The random () method
the Math.random () method returns a random number greater than or equal to 0 less than 1 . For some sites, this method is useful because it can be used to randomly display some famous sayings and news events. Using the following formula, you can use Math.random () to randomly select a value from within an integer range.
Value = Math.floor (Math.random () * Total number of possible values + first possible value)

The Math.floor () method is used in the formula because Math.random () always returns a small value. By multiplying the decimal value by an integer and then adding an integer, the final result is still a decimal. For example, if you want to choose a value from 1 to 10, you can write code like this:
var num = Math.floor (math.random () * 10 + 1);

There are a total of 10 possible values (1 to 10), and the first possible value is 1. If you want to select a value between 2 and 10, you should change the above code to this:
var num = Math.floor (math.random () * 9 + 2);

The number from 2 to 10 is 9, so the total number of possible values is 9, and the first possible value is 2. In most cases, you can actually use a function to calculate the total number of possible values and the first possible value, for example:
function Selectfrom (Lowervalue, Uppervalue) {
var choices = Uppervalue-lowervalue + 1;
Return Math.floor (Math.random () * choices + lowervalue);
}
var num = Selectfrom (2, 10);
alert (num); A numeric value between 2 and 10 (including 2 and 10)

The function Selectfrom () accepts two parameters: the minimum and maximum values that should be returned. The maximum value minus the minimum value plus 1 gets the total number of possible values, and then it applies these values to the previous formula. This allows you to get a value between 2 and 10 (including 2 and 10) by calling Selectfrom (2,10). This function makes it easy to take an item randomly from an array, for example:
var colors = ["Red", "green", "blue", "yellow", "black", "purple", "Brown"];
var color = colors[selectfrom (0, colors.length-1)];
Aler t (color); May be any one of the strings contained in the array

In this example, the second argument passed to Selectfrom () is the length of the array minus 1, which is the position of the last item in the array.
5. Other methods
The Math object also contains other methods related to completing various simple or complex calculations, but the details and applicability of each of these methods are beyond the scope of this book. Here we give a table that lists the methods of the math objects that are not covered.

Although ECMA-262 prescribes these methods, different implementations may use different algorithms for these methods. After all, there are various ways to calculate the sine and cosine and tangent of a value. Because of this, these methods may have different precision in different implementations.

"JavaScript Advanced Program Design" Reading notes---monomer built-in objects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.