Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand single built-in objects in JavaScript

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to understand single built-in objects in JavaScript, and the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

ECMA-262 defines built-in objects as "objects provided by the JavaScript implementation that are not dependent on the host environment, and these objects exist before the JavaScript program executes." This means that developers do not have to explicitly instantiate built-in objects because they are already instantiated. We have already introduced most of the built-in objects, such as Object, Array, and String. ECMA-262 also defines two single built-in objects: Global and Math.

Global object

The Global object can be said to be the most special object in JavaScript, because no matter how you look at it, it doesn't exist. In a sense, the Global object is defined as a "backing object". In other words, properties and methods that do not belong to any other object are ultimately its properties and methods. All properties and functions defined in the global scope are properties of the Global object. The functions described earlier in this book, such as isNaN (), isFinite (), parseInt (), and parseFloat (), are actually all methods of the Global object. In addition, the Global object contains other methods.

URI coding method

The encodeURI () and encodeURIComponent () methods of the Global object can encode the URI (Uniform Resource Identifiers, universal resource identifier) for sending to the browser. Valid URI cannot contain certain characters, such as spaces. These two URI encoding methods can encode URI, replacing all invalid characters with a special UTF-8 encoding, so that browsers can accept and understand it.

Among them, encodeURI () is mainly used for the entire URI, while encodeURIComponent () is mainly used to encode a segment in the URI. The main difference is that encodeURI () does not encode special characters that belong to URI itself, such as colons, forward slashes, question marks, and pit symbols, while encodeURIComponent () encodes any non-standard characters it finds. Let's look at the following example.

Var uri = "http://shijiajie.com/illegal value.htm#start"; console.log (encodeURI (uri)); / / "http://shijiajie.com/illegal%20value.htm#start" console.log (encodeURIComponent (uri)); / /" http%3A%2F%2Fshijiajie.com%2Fillegal%20value.htm%23start "

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

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

The two methods corresponding to the encodeURI () and encodeURIComponent () methods are decodeURI () and decodeURIComponent (), respectively. Where decodeURI () can only decode characters replaced with encodeURI (). For example, it can replace% 20 with a space, but will not do anything with% 23, because% 23 represents the hyphen # and the hyphen 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%2Fshijiajie.com%2Fillegal%20value.htm%23start"; console.log (decodeURI (uri)); / / http%3A%2F%2Fshijiajie.com%2Fillegal value.htm%23start console.log (decodeURIComponent (uri)); / / http://shijiajie.com/illegal value.htm#start

Here, the variable uri contains a string encoded by encodeURIComponent (). In the result of * calls to decodeURI () output, only% 20 has been replaced with spaces. In the result of the second call to decodeURIComponent (), the encoding of all the special characters is replaced with the original character, resulting in an unescaped string (but this string is not a valid URI).

Eval () method

The eval () method is like a full JavaScript parser, accepting only one parameter, the JavaScript string to execute. Look at the following example:

Eval ("console.log ('hi')")

This line of code is equivalent to the following line of code:

Console.log ("hi")

When the parser finds that the eval () method is called in the code, it parses the passed parameters as the actual JavaScript statement, and then inserts the execution result into the original location. The code executed through eval () is considered to be part of the execution environment that contains the call, so the code being executed has the same chain of scope as the execution environment. This means that code executed through eval () can refer to variables defined in the containing environment, for example:

Var msg = "hello world"; eval ("console.log (msg)"); / / "hello world"

It can be seen that the variable msg is defined outside the context of the eval () call, but the called console.log () can still display "hello world". This is because the second line of code above is finally replaced with a real line of code. Similarly, we can define a function in the eval () call, and then reference the function in the external code of the call:

Eval ("function sayHi () {console.log ('hi');}"); sayHi (); / / "hi"

Obviously, the function sayHi () is defined inside eval (). But 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';"); console.log (msg); / / "hello world"

Any variables or functions created in eval () are not promoted because they are contained in a string when the code is parsed; they are only created when eval () is executed.

In strict mode, there is no external access to any variables or functions created in eval (), so the first two examples result in errors. Similarly, in strict mode, assigning a value to eval also results in an error:

"use strict"; eval = "hi"; / / causes error

The ability to interpret code strings is very powerful, but also very dangerous. Therefore, great care must be taken when using eval (), especially if it is used to execute user input data. Otherwise, malicious users may enter code that threatens the security of your site or application (so-called code injection).

Properties of the Global object

The Global object also contains some properties, some of which have been described earlier in this book. For example, the special values undefined, NaN, and Infinity are all properties of the Global object. In addition, constructors of 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.

Attribute description attribute description undefined special value undefinedDate constructor DateNaN special value NaNRegExp constructor RegExpInfinity special value InfinityError constructor ErrorObject constructor ObjectEvalError constructor EvalErrorArray constructor ArrayRangeError constructor RangeErrorFunction constructor FunctionReferenceError constructor ReferenceErrorBoolean constructor BooleanSyntaxError constructor SyntaxErrorString constructor TypeErrorNumber constructor NumberURIError constructor URIError

ECMAScript 5 explicitly forbids assigning values to undefined, NaN, and Infinity, which results in errors even in non-strict mode.

Window object

Although JavaScript does not indicate how to access the Global object directly, Web browsers implement this global object as part of the window object. Therefore, all variables and functions declared in the global scope become properties of the window object. Let's look at the following example.

Var color = "red"; function sayColor () {console.log (window.color);} window.sayColor (); / / "red"

The window object in JavaScript not only plays the role of the specified Global object, but also undertakes many other tasks.

Math object

JavaScript also provides a common place to hold mathematical formulas and information, that is, Math objects. The computing capabilities provided by the Math object are much faster to perform than the computing functions we wrote directly in JavaScript. Properties and methods to assist in these calculations are also provided in the Math object.

Properties of the Math object

Most of the properties contained in the Math object are special values that may be used in mathematical calculations. These attributes are listed in the following table.

Attribute description

The attribute describes the base of the natural logarithm of Math.E, that is, the value of constant e, the natural logarithm of Math.LN1010, the natural logarithm of Math.LN22, the logarithm of Math.LOG2E with base 2, the logarithm of e, the square root of Math.PI π, the square root of Math.SQRT1_21/2 (that is, the reciprocal of the square root of 2), the square root of Math.SQRT22.

Min () and max () methods

The Math object also contains many methods to assist in simple and complex mathematical calculations. The min () and max () methods are used to determine the minimum and * * 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); console.log (max); / / 54 var min = Math.min (3,54,32,16); console.log (min); / / 3

To find the * * or minimum 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); console.log (max); / / 8

The key to this technique is to set the this value correctly by taking the Math object as the * * parameter of apply (). You can then take any array as the second parameter.

Rounding method

Here are several ways to round decimal values to integers: Math.ceil (), Math.floor (), and Math.round (). These three methods follow the following rounding rules, respectively:

Math.ceil () performs up rounding, that is, it always rounds the value up to the nearest integer

Math.floor () performs down rounding, that is, it always rounds the value down to the nearest integer

Math.round () performs standard rounding, that is, it always rounds the number to the nearest integer.

The following is an example of using these methods:

Console.log (Math.ceil 25.9); / 26 console.log (Math.ceil 25.5); / 26 console.log (Math.ceil 25.1); / 26 console.log (Math.round 25.9); / 26 console.log (Math.round 25.5); / 26 console.log (Math.round 25.1); / 25 console.log (Math.floor 25.9) / / 25 console.log (Math.floor 25.5); / 25 console.log (Math.floor (25.1)); / / 25

Random () method

The Math.random () method returns a random number between 0 and 1, excluding 0 and 1. For some sites, this method is very useful because it can be used to randomly display celebrity quotes and news events. Applying the following formula, you can use Math.random () to randomly select a value from a range of integers.

Value = Math.floor (Math.random () * Total number of possible values + * possible values)

The Math.floor () method is used in the formula because Math.random () always returns a decimal value. Multiply this decimal value by an integer, and then add an integer, and the final result is still a decimal. For example, if you want to choose a value between 1 and 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), while * possible values are 1. If you want to choose a value between 2 and 10, you should change the above code like this:

Var num = Math.floor (Math.random () * 9 + 2)

There are nine numbers from 2 to 10, so the total number of possible values is 9, and the possible values are 2. In most cases, you can actually use a function to calculate the total number of possible values and * possible values, such as:

Function selectFrom (lowerValue, upperValue) {var choices = upperValue-lowerValue + 1; return Math.floor (Math.random () * choices + lowerValue);} var num = selectFrom (2,10); console.log (num); / / a number between 2 and 10 (inclusive)

The function selectFrom () takes two parameters: the minimum value that should be returned and the * * value. Using the * * value minus the minimum value plus 1 to get the total number of possible values, and then it applies these values to the previous formula. In this way, you can get a value between 2 and 10 (including 2 and 10) by calling selectFrom (2 no. 10). With this function, you can easily fetch an item randomly from the array, such as:

Var colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"]; var color = colors [selectFrom (0, colors.length-1)]; console.log (color); / / any string that may be contained in the array

Other methods

The Math object also contains other methods related to completing a variety of simple or complex calculations, but a detailed discussion of the details and applicability of each of these methods is beyond the scope of this book. Below we give a table that lists the methods of these Math objects that are not covered.

The method explains that Math.abs (num) returns the absolute value of num Math.asin (x) returns the arc tangent value of x Math.exp (num) returns the num power of Math.E Math.atan (x) returns the arc tangent value of x Math.log (num) returns the natural logarithm of num Math.atan2 (y num x) returns the arc tangent value Math.pow (num) of y Power) returns the power power of num Math.cos (x) returns the cosine of x Math.sqrt (num) returns the square root of num Math.sin (x) returns the sine of x Math.acos (x) returns the inverse cosine of x Math.tan (x) returns the tangent of x

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

/ / how to efficiently generate non-repetitive random numbers in the range of m n (m

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report