JavaScript = = Operational details _ Basic knowledge

Source: Internet
Author: User
Tags abstract numeric

As you know, JavaScript = = = is a more complex operation, and its operating rules are very strange, it is easy to make people wrong, thus becoming one of the "worst features" in JavaScript.

On the basis of the careful reading of the ECMAScript specification, I drew a picture, I think after you understand this picture, will thoroughly understand all about = = operation. At the same time, I tried to prove to everyone in this article that = = is not so bad things, it is easy to grasp, even look reasonable, and not so bad.

First figure:

= = The exact description of the operation rules here: the Abstract equality Comparison algorithm. But, with such a complicated description, are you sure your brain is not dizzy after you read it? Sure you can use it to guide practice immediately?

Certainly not, the spec is for developers of JavaScript-running environments (compared to V8 engine developers), not for language users. The above diagram is to translate the specification into a convenient form for everyone to see.

Before detailing each of the sections in Figure 1, let's review the knowledge about types in JS:

There are two types of values in JS: base type, object type.
Basic types include five types: Undefined, Null, Boolean, number, and string.
Both the undefined type and the null type have only one value, that is, the undefined and Null;boolean types have two values: True and False;number types have a number of values, and string values have countless values (in theory).
All objects have valueof () and ToString () methods, which inherit from object and, of course, may be overridden by the quilt class.
Now consider an expression:

x = = y
where x and y are values of one type in six types.

When the type of x and Y is the same, x = = y can be converted to x = = y, and the latter is very simple (the only thing to be aware of is Nan), so let's just consider the different types of x and Y.

I. There and none

In Figure 1, the six types of JavaScript values are represented by a rectangle with a blue background. First they are divided into two groups:

String, Number, Boolean, and object (large rectangular box to the left)
Undefined and null (corresponding rectangular box to the right)
What is the basis for grouping? Let's take a look at the undefined and null on the right to indicate uncertainty, absence, or emptiness, while the four types on the right are OK, yes, and non-null. We can say this:

Left is a world of existence, on the right is an empty world.
Therefore, it is reasonable for any value in the left and right worlds to do the result of = = comparison. (That is, false on the horizontal line with two rectangles connected in Figure 1)

Two. Empty and empty

The undefined and null in JavaScript are another place that often crashes us. Usually it is considered a design flaw, which we do not delve into. But I've heard that the authors of JavaScript initially thought:

If you're going to assign a variable to the value of the object type, but there is no assignment now, so you can use NULL to indicate the state at this time (one of the evidences is that the result of typeof null is ' object '); instead, if you're going to give a variable a value of the original type, but it's not yet assigned, Then you can use undefined to indicate the state at this time.
Whether or not this rumor is believable, it is reasonable to compare the results of the two as equals. (That is, true on the right vertical line in Figure 1)

Before we move on to the next step, let's start with the two symbols in Figure 1: Uppercase N and P. These two symbols are not the positive and negative meaning of the PN section. But:

n represents the Tonumber operation, which turns the operand into a number. It is an abstract operation in the ES specification, but we can use the number () function in JS to replace the equivalent.
P represents the toprimitive operation, which turns the operand into a value of the original type. It is also an abstract operation in the ES specification, which can also be translated into the equivalent JS code. But a little more complicated, to put it simply, for an object obj:
Toprimitive (obj) is equivalent to: First compute obj.valueof (), if the result is the original value, return this result, otherwise, calculate obj.tostring (), and if the result is the original value, return this result;
Note: Here is an exception, a date-type object that invokes the ToString () method first.

In Figure 1, a line labeled N or P indicates that when the two types of data it connects to do the = = operation, the operands marked with N or P must first perform tonumber or toprimitive transformations.

Three. True and False

As you can see from Figure 1, when a Boolean value is compared to a value of another type, the Boolean value is converted to a number, specifically

True-> 1
False-> 0
This does not need to waste too much tongue. Think about it. In the C language, there is no Boolean type, which is usually used to represent the logic of true and false integers 1 and 0.

Four. Sequence of characters

In Figure 1, we divide the string and number into a group. Why, then? In six types, string and number are sequences of characters (at least literally). A string is a sequence of all valid characters, and a number can be seen as a sequence of characters that match a particular condition. So, numbers can be viewed as a subset of strings.

As shown in Figure 1, the string and number are used to perform the = = operation, and the string is converted to a number by using the Tonumber action. Assuming X is a string and Y is a number, then:

x = = y-> number (x) = = y
So what are the rules for converting strings into numbers? The specification is complicated, but in general it's about removing the quotes on either side of the string and seeing if it can make up a legitimate number. If so, the conversion result is the number, otherwise the result is Nan. For example:

Number (' 123 ')//result 123
Number (' 1.2e3 ')//Result 1200
Number (' 123ABC ')//Result Nan
There are, of course, exceptions, such as the result of an empty string being converted to a number 0. That

Number (')//Result 0

Five. Simplicity and complexity

The original type is a simple type, which is straightforward and easy to understand. However, the disadvantage is that the ability to express limited, difficult to expand, so there are objects. An object is a collection of attributes, and the property itself can be an object. So objects can be constructed arbitrarily complex enough to represent all sorts of things.

But sometimes it's not good to be complicated. For example, a long paper, not everyone has time, patience or need to read from start to finish, usually only understand the central idea is enough. So the paper has a keyword, overview. The object in JavaScript is the same, we need a means to understand its main characteristics, so the object has the ToString () and valueof () method.

The ToString () method is used to get a textual description of the object, while the valueof () method is used to get the object's eigenvalues.
Of course, it's just my own understanding. Also, as the name suggests, 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 the valueof () method returns only number and date in the built-in type.

According to Figure 1, when an object is compared to a non object, the object needs to be converted to the original type (although the Boolean type is required to be a numeric type when compared to a Boolean type, but the object type is then changed to the original type). This is also reasonable, after all = = is not strict equality comparison, we only need to take out the main features of the object to participate in the operation, the secondary features on the side of the line.

Six. Everything counts

Let's look back at Figure 1. The lines marked with n or P have no direction. If we mark the arrows on these lines, and the line points to the other end from the end labeled N or P, you get (regardless of undefined and null):

Have you found anything yet? Yes, all types of values have a tendency to convert to numeric types during the operation process. After all, there were celebrities who said:

All things are counted.

Seven. Barely raise a chestnut

There is too much nonsense in front of you, here is an example to prove that figure 1 is really convenient and effective to guide practice.

example, calculate the following:

['] = = False
First, the two operands are object type and Boolean type respectively. According to Figure 1, the Boolean type needs to be converted to a numeric type, and false to the result of a number is 0, so the expression becomes:

["] = = 0
Two operands became object type and number type. According to Figure 1, the object type needs to be converted to the original type:

Call [].valueof () First, because the valueof () method of the array returns itself, so the result is not the original type, and the call to [].tostring () continues.
For arrays, the algorithm for the ToString () method is to convert each element to a string type and then ', ' to concatenate, so that the end result is an empty string ', which is a value of the original type.
At this point, the expression becomes:

"' = 0
Two operands have become string types and numeric types, and according to Figure 1, the string type needs to be converted to a numeric type, preceded by an empty string that turns the number 0. The expression then becomes:

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

As you can see from this example, in addition to remembering figure 1, you need to remember the rules for the ToString () and valueof () methods of the built-in objects in order to master the rules of the = = operation. Includes object, Array, Date, Number, String, Boolean, and so on.

Eight. To sum up

It's a mess, and here's a summary of the rules for the = = operation expressed in Figure 1:

The result of undefined = = NULL is true. Both of them are false in comparison with all other values.
String = = number, strings are converted to numbers.
Boolean value = = Other Type, the Boolean value is converted to a number.
Object = = number/String, the object is converted to the base type.
Finally, change the picture for entertainment only:

OK, it's over. If you think this article is useful to you, please point it out and let more people see it.
In addition, the fallacy of the article, please do not hesitate to point out.

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.