The problem of = = in the logical operator in JS

Source: Internet
Author: User
Tags number sign object object

Frankly speaking, JS = = is more depth than the mathematics of = =, is called "the worst Effect" one.

I looked up a lot of information and thanked our predecessors. Here, in order to warm and know the new, summed up:

A. Remember the rules of the = = Operation:

(1) undefined = = NULL, the result is true. And the result of comparing them to all other values is false.

If you are going to assign a variable to the value of the object type, but you have not yet assigned a value, you can use it to null represent the state at this point (one typeof null of the evidences is the result object );

Conversely, if you are going to assign a variable to a value of the original type, but you have not yet assigned a value, you can use it to undefined represent the state at this point.

Both the ①undefined type and the null type have only one value, that is, undefined and null, both null, so the result of undefined = = NULL is true reasonable.

② inside the cast method:

Convert to Numeric type: Number(Mix),parseint (string,radix),parsefloat (string)

Convert to String type: toString (radix),string (Mix)

Convert to Boolean type:Boolean (Mix)

No one can convert them to both, so the result of comparing them to all other values is false.

(2) String = = Boolean, which requires two operands to be converted to number at the same time.

(3) String/boolean = = number, need String/boolean to number.

String, Blooean, number three types in (2) and (3) are basic data types except for undefined and null.

These three kinds of 22 comparisons are first turned into number before comparing the results.

A Boolean has only two values: True and False, converted to number:true-->1 false-->0

Chestnuts are as follows:

Comparison of strings to numbers
Console.log (' 1 ' = = 1); True
Comparison of strings to Boolean values
Console.log (' 0 ' = = false); True
Comparison of numbers with Boolean values
Console.log (1 = = true); True


Comparison of numbers and numbers
Console.log (1 = = 1); True

A comparison of Boolean values with Boolean values
Console.log (false = = false); True
String vs. String
Console.log (' 1 ' = = ' 1 '); True
Console.log (' 4a ' = = ' f '); False

Note the contrast between strings, if not a pure numeric string, the comparison between strings is based on the ASCII table values, and if the first value is equal, compare the second ... As long as the ASCII value is obtained, there is no need to compare. In general, string comparisons need to be identical in order to be equal.

Strings are more special:

Console.log (Number (NULL));//0Console.log (number (undefined));//NaNConsole.log (Number (")");//0Console.log (Number (")");//0Console.log (number (0));//0Console.log (Number (' head good halo '));//NaNConsole.log (number (' 0.0 '));//0Console.log (Number (' 100px '));//NaNConsole.log (Number ('-10 '));//-10//rule: Number () only supports numeric strings, except for empty strings, space strings;

(4) Object = = Primitive, requires object to be Primitive (specifically through the valueof () and ToString () methods).

The ToString () method is used to get a textual description of the object, whereas the valueof () method is used to get the eigenvalues of the object.

As the name implies, the toString () method tends to return a string. The ValueOf () method, as described in the specification, tends to return a number-although the ValueOf () method returns a number and date only in the built-in type.

The following table lists the return values of the object's valueof ():

Object return value
Array The elements of the array are converted to strings, which are separated by commas and concatenated together. The operation is the same as the array.tostring and Array.join methods.
Boolean A Boolean value.
Date The stored time is the number of milliseconds that are counted from midnight January 1, 1970 UTC.
Function function itself.
Number numeric value.
Object The object itself. This is the default condition.
String The string value.

    • ToString (radix) method. Values of all types except undefined and null have the ToString () method, which is the function of returning the string representation of an object.

Object Operation
Array Converts the element of an Array to a string. The resulting strings are separated by commas and joined together.
Boolean Returns "true" if the Boolean value is true. Otherwise, return "false".
Date Returns the literal representation of the date.
Error Returns a string containing the associated error information.
Function Returns a string in the following format, where functionname is called by the ToString method function name: function functionname () {[native code]}
Number Returns the literal representation of a number.
String Returns the value of a String object.
Default Returns "[Object ObjectName]", where ObjectName is the name of the object type.

When an object is compared to a non-object, the object needs to be converted to the original type, and the Boolean type becomes the numeric type.

Give a chestnut: Console.log (['] = = false); True

(1) First, the two operands are object type, Boolean type, respectively. You need to convert the Boolean type to a numeric type, and false to a number results in 0, so the expression becomes: ['] = = 0, two operands become object type, number type.

(2) The object type needs to be converted to the original type:

First Call [].valueof (), because the array's valueOf () method returns itself, so the result is not the original type, continue to call [].tostring ().

For arrays, the ToString () method's algorithm is to convert each element to a string type and then concatenate it with a comma, so the end result is an empty string ', which is a value of the original type.

At this point, the expression becomes: ' = = 0, two operands become a string type, a numeric type.

(3) You need to convert the string type to a numeric type, which says that the empty string becomes a number 0. Then the expression becomes: 0 = = 0

The result is obviously true.

Give another chestnut: Console.log ({} = = false);//false

  Console.log ({}.valueof ()); // {}  Console.log ({}.tostring ());   ' [Object Object]'  false); // false

Two. Supplement:

1.How to determine the six big data types in JS?

(1) In terms of primitive types and complex types:
Primitive types (Primitive) include: Undefined, Null, Boolean, number, and string five primitive types, object types (objects).

(2) The typeof gets the type: Undefined, Function, Boolean, number, string, and object.

2. Whatis the difference between the basic data type and the reference data type in JS?

A variable of the JS base data type holds the actual value of the underlying type data, while a variable of the reference data type holds a reference to it, the pointer.

(1) JS basic data type: null, undefined, number, Boolean, string comparison special
(2) Reference data type: function Object array
such as:

var a = one; var b ==//11==> A value does not change as B is worth to change var c = [n/a]; var d = a;c[0] = 2; the value ofconsole.log (d[//2==> B is changed with the value of a. Because they point to the same memory address

3. Cast:

Number (mix) function, you can convert any type of parameter mix to a numeric type. The rules are:

(1) If it is a Boolean value, True and false are converted to 1 and 0 (2) If it is a numeric value, which returns itself. (3) If NULL, returns 0. (4) If it is undefined, return nan. (5) If it is a string, follow these rules:1If the string contains only numbers, convert it to decimal (ignoring leading 0)2, if the string contains a valid floating-point format, convert it to a floating-point value (ignoring leading 0) 3.If it is an empty string, convert it to 04, convert it to Nan (6) If the string contains a non-above format, if it is an object, call the object's valueof () method, and then convert the returned value based on the preceding rule. If the result of the conversion is Nan, the object's ToString () method is called, and the returned string value is converted again according to the previous rule.

The parseint (string, radix) function converts a string to a numeric value of type Integer. It also has certain rules:

(1) ignore the space in front of the string until the first non-null character is found (2) If the first character is not a number sign or minus sign, return Nan (3) If the first character is a number, The parsing continues until the string parsing is complete or a non-numeric symbol is encountered (4) If the result of the step-up parsing starts with 0, it is parsed as an octal, and if it starts with X, it is parsed as hexadecimal (5) If the radix parameter is specified, The radix is the base of the analysis

The parsefloat (string) function converts a string to a numeric value of a floating-point number type.

Its rules are basically the same as parseint, but there is a difference: the first decimal symbol in a string is valid, and parsefloat ignores all leading 0, and if the string contains a number that resolves to an integer, the integer value is returned instead of the floating-point value.

String (mix) function that converts any type of value to a string with the following rule:

(1) If there is a ToString () method, call the method (do not pass the radix parameter) and return the result (2) If it is null, return "null" (3) If it is undefined, return " Undefined

Boolean (Mix) function to convert any type of value to a Boolean value:

the following values are converted to false: false, "", 0, NaN, null, undefined, and any other value will be converted to true. 

The original reference to the following two bits greatly:

Https://www.cnblogs.com/yangyang63963/p/5916396.html

Https://www.cnblogs.com/Juphy/p/7085197.html

If there are errors, welcome treatise!!!

The problem of = = in the logical operator in JS

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.