JavaScript = operation details, javascript Operation Details

Source: Internet
Author: User

JavaScript = operation details, javascript Operation Details

As you know, = in JavaScript is a complicated operation. Its operation rules are very strange and easy to make mistakes, making it one of the "worst features" in JavaScript.

After carefully reading the ECMAScript specification, I drew a picture. After understanding this picture, I want to thoroughly understand everything about =. At the same time, I tried to prove through this article that = is not so bad, it is easy to grasp, and even looks reasonable, not so bad.

First:

= The exact description of The operation rule is here: The Abstract computing ity Comparison Algorithm. However, are you sure you are not dizzy after reading this complicated description? Are you sure you can use it to guide your practice immediately?

Certainly not. The specifications are for developers in the JavaScript Runtime Environment (compared with those of the V8 engine), rather than for language users. It is just to translate the specifications into a form that is easy for everyone to see.

Before giving a detailed description of each part in Figure 1, let's review the type knowledge in JS:

JS has two types of values: basic type and object type.
The basic types include Undefined, Null, Boolean, Number, and String.
Both the Undefined and Null types have only one value, namely, undefined and null. The Boolean type has two values: true and false. The Number type has many values; the number of values of the String type (theoretically ).
All objects have the valueOf () and toString () methods. They inherit from the Object and may also be overwritten by the quilt class.
Now consider the expression:

X = y
X and y are values of one of the six types.

When the types of x and y are the same, x = y can be converted to x = y, while the latter is very simple (the only thing to note is NaN ), therefore, we will only consider the different types of x and y.

I. Have and none

In Figure 1, the six types of JavaScript values are represented by blue-colored rectangles. First, they are divided into two groups:

String, Number, Boolean, and Object (corresponding to the large rectangle on the left)
Undefined and Null (corresponding to the rectangle on the right)
What is the basis of grouping? Here, the Undefined and Null values on the right are used to indicate Undefined, Null, or Null, while the four types on the right are definite, with and without Null. We can say this:

There is a world on the left and an empty world on the right.
Therefore, it is reasonable to make the = comparison result of any value in both the left and right worlds false. (That is, the horizontal line mark connecting two rectangles in Figure 1 is false)

2. Empty and empty

Undefined and null in JavaScript are another place that often causes us to crash. Usually it is regarded as a design defect, which we will not go. However, I have heard that the author of JavaScript initially thought like this:

If you want to assign a variable to a value of the object type, but no value is assigned yet, then you can use null to indicate the state at this time (one of the evidence is that typeof null results in 'object'). On the contrary, if you want to assign a variable to a value of the original type, but no value has been assigned yet, so you can use undefined to indicate the status at this time.
Whether the rumor is credible or not, it is reasonable to compare the two =. (True)

Before proceeding to the next step, let's talk about the two symbols in 1: uppercase letters N and P. These two symbols do not mean positive and negative in the PN section. But:

N indicates the ToNumber operation, which converts the operand to a number. It is an abstract operation in ES specifications, but we can replace it with the Number () function in JS.
P indicates the ToPrimitive operation, which converts the operand to the value of the original type. It is also an abstract operation in ES specifications. It can also be translated into equivalent JS Code. But it is a little more complicated. In short, for an object obj:
ToPrimitive (obj) is equivalent to: Calculate obj first. valueOf (). If the result is the original value, this result is returned. Otherwise, obj is calculated. toString (). If the result is the original value, this result is returned. Otherwise, an exception is thrown.
Note: there is an exception here, that is, an object of the Date type, which calls the toString () method first.

In Figure 1, the line labeled with N or P indicates that when it connects two types of data for the = operation, the operands on the side marked with N or P must first perform the ToNumber or ToPrimitive transformation.

3. true and false

As shown in figure 1, when the Boolean value is compared with other types of values, the Boolean value is converted to a number. Specifically

True-> 1
False-> 0
This does not need to be wasted. In C, there is no boolean type at all. It is usually used to indicate that the logic is true and false, Which is exactly integer 1 and 0.

Iv. Character Sequence

In Figure 1, we divide String and Number into a group. Why? In the six types, String and Number are character sequences (at least literally ). A string is a sequence of all valid characters, and a number can be considered as a sequence of characters that meet specific conditions. Therefore, numbers can be considered as a subset of strings.

According to Figure 1, when performing the = operation on strings and numbers, you need to use the ToNumber operation to convert strings into numbers. Assume that x is a string and y is a number:

X = y-> Number (x) = y
What are the rules for converting strings into numbers? The description in the specification is very complex, but in general, it is to remove the quotation marks on both sides of the string and then see if it can form a legal number. If yes, the conversion result is the number. Otherwise, the result is NaN. For example:

Number ('20140901') // Result 123
Number ('1. 2e3 ') // result 1200
Number ('123abc') // result NaN
Of course, there are also exceptions. For example, the result of converting a null string to a number is 0. That is

Number ('') // result 0

5. simplicity and complexity

Primitive types are simple types that are straightforward and easy to understand. However, the disadvantage is that the expression capability is limited and it is difficult to expand, so there is an object. An object is a set of attributes, and an attribute itself can be an object. Therefore, objects can be constructed as complicated as they are to represent various things.

However, sometimes complicated things are not a good thing. For example, not everyone has time, patience, or need to read a long paper from start to end. Generally, it is enough to understand only the central idea. So the paper has a keyword and an overview. The same is true for objects in JavaScript. We need a means to understand its main features, so the object has the toString () and valueOf () methods.

The toString () method is used to obtain a text description of an object, while the valueOf () method is used to obtain the feature value of an object.
Of course, this is just my own understanding. In addition, as the name implies, the toString () method tends to return a string. What about the valueOf () method? According to the description in the Specification, it tends to return a Number-although in the built-in type, the valueOf () method returns only Number and Date.

According to Figure 1, when an object is compared with a non-object, the object needs to be converted to the original type (although compared with the boolean type, the Boolean Type needs to be converted to the numeric type first, but next we need to change the object type to the original type ). This is also reasonable. After all, = is not strict equal comparison. We only need to extract the main features of the object for calculation, and the secondary features can be put aside.

6. Full Data

Let's look back at 1. There is no direction for the lines marked with N or P. If we place an arrow on these lines to point the line from the end labeled N or P to the other end, we will get (undefined and null are not considered ):

Have you found anything? Yes, during the operation, all types of values have a tendency to convert to the numeric type. After all, celebrities once said:

Everything is in number.

7. Barely raise a chestnut

There are too many nonsense. Here is an example to prove that figure 1 is indeed convenient and effective and can guide the practice.

Example:

[''] = False
First, the two operands are of the object type and boolean type. According to Figure 1, convert the boolean type to the numeric type, and convert the false type to the numeric type to 0. Therefore, the expression is changed:

[''] = 0
The two operands are converted to the object type and number type. According to Figure 1, you need to convert the object type to the original type:

First, call []. valueOf (). Because the valueOf () method of the array returns itself, the result is not of the original type. Continue to call []. toString ().
For arrays, The toString () method is used to convert each element into a string type and connect it with ','. Therefore, the final result is a Null String '', it is a value of the original type.
In this case, the expression is changed:

''= 0
The two operands are converted to the string type and numeric type. according to Figure 1, the string type needs to be converted to the numeric type. As mentioned above, the empty string is converted to the number 0. The expression is changed:

0 = 0
So far, the two operands are of the same type, and the result is obviously true.

From this example, we can see that to grasp the = operation rules, in addition to keeping in mind figure 1, we also need to remember the rules of the toString () and valueOf () Methods of the built-in objects. Including Object, Array, Date, Number, String, and Boolean.

8. Summary

As mentioned above, we will summarize the = calculation rules in section 1:

The result of undefined = null is true. The result of comparing them with all other values is false.
String = number, the string is converted to a number.
If the Boolean value is = another type, the Boolean value is converted to a number.
When the object = Number/string, the object is converted to the basic type.
Finally, I changed the figure for entertainment only :)

OK. If you think this article is useful to you, please like it and let more people see it.
In addition, please leave it empty.

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.