== javascript implicit conversion of [] ==! [] to true, and {} ==! The result is false {}

 

In ECMAScript == implicit conversion is converted into the first sides of a similar type, and then performs a comparison;

①, if either operand is a Boolean value, before comparing for equality first convert --false converted value is 0, and is converted to true. 1;
②, if the operand is a string, the other operand is a number, the first string into a numerical value before the comparison equality
③, if the operand is a target, the other operand is not, the object is invoked valueOf () method, in accordance with the preceding rules primitive values obtained Compare, if the object does not have valueOf () method, then call toString ();

Incidentally, valueOf () method returns the Boolean value of the original object. [] {} Belong and a reference type, js stack storage variable is stored and heap memory, basic data types of variables are stored in the stack, the reference data type of variables are stored in the heap, the reference address data type is present in the stack, when accessing basic types of variable values ​​directly from the stack. When accessing a reference type variable, the read address start with the stack, the stack to extract data from the address;

 ! Now look at [] == [] evaluates to true:

(1) The operator precedence,! The priority is greater than ==, it will first execute []!;! It can be converted into a boolean variable type, null, undefined, NaN and an empty string ( '') are the inverse is true, the rest are false. ! So [] it is the result of the calculation false, i.e. [] == [] is equivalent to [] to false ==!;

! (2) ① According to the above rules, [] == [] is equivalent to [] == 0;

(3) According to the above rule ③, [] .toString () = '' (the empty string);

(4) According to the above rules into ②, empty string value is 0, the [] ==! [] = 0 corresponds to 0, the result is true.

in conclusion:

[ ] ==![ ]  -->  [ ] == false  -->  [ ] ==0  -->   '  ' == 0   --> 0==0 --> true;

! For == {} {} is the same token, the key is {} .toString () -> the result is NaN, NaN == 0 -> false;

So the same token,

! For [] {} == result to true;! == {} [] If false then very easy to understand.

Guess you like

Origin www.cnblogs.com/jny1990/p/10956996.html