There are "= =" and "= = =" In JavaScript, so what is the difference between them?
For the base data type, = = = (!==) returns true only if the type and value of the two variables are equal, whereas = = (! =) enforces the type conversion of the variable , returning True if the converted value is equal.
The following code tells you about the basic rules of forced transformation that are followed by the equality = = and unequal! = operators when converting different data types:
1. If one operand is a Boolean, convert it to a numeric value before comparing equality: false to 0, and true to 1;
false = = 0 //truetrue = = 1 //truetrue = = 3 //false
2. If one operand is a string and the other operand is a numeric value, the string is converted to a numeric value before equality is compared;
"123" = = 123 //true
3. If one operand is an object and the other operand is not, then the valueof () method of the object is called, and the resulting base type value is compared with the preceding rule;
var a = [1, 2, 3= = "A.valueof") //true, the
It is important to note that:
A. Null and undefined are equal, and null and undefined cannot be converted to any other value;
null = = undefined //trueundefined = = 0 //falsenull = = 0 //false false //falsenullFalse //false
B. If one of the operands is Nan, the equality operator = = Returns false, and the inequality operator! = Returns TRUE.
Tips: Even though the two operands are Nan, the equality operator = = also returns False, because Nan is not equal to Nan by rule.
Nan = = Nan //falsenan! = nan //truenan = = 0 //False
C. If the two operands are objects, compare them to the same object. The equality operator returns TRUE if all two operands point to the same object, otherwise, false is returned.
var New Object () var New Object () var obj2 =//false//true//false
In addition, what is the case that JS code needs to be forced to transform the variable?
1. String concatenation:
var a = 1 + 1 // 2var b = 1 + "1" // One
2. If statements are judged:
if { alert(+) // will execute }if(!0) { alert (0) // will not execute } if (! NULL { alert (null) // will not execute }if(! Undefined) { alert (undefined) // will not execute }
3. Logical operators
Alert (&& 0) //0alert (' | | | ' AB ') //' ab 'alert (!0) //truealert (!! +) //true
PS: && (Logic and) and | | These two logical operators do not necessarily return Boolean values, and both follow the short-circuit principle. Write a separate essay tomorrow!
So when do we use = = when to use = = =?
A: Because of the problem of type conversion for equality = = and inequality operator! =, in order to maintain the integrity of the data types in the code, Red Cookbook recommends that we try to use the congruent = = And not equal! = operator. In jquery, there is one such notation:
if NULL ) { // equals obj.a = = = NULL | | obj.a = = = undefined abbreviated }
In addition, we all use = = =.
If there are errors, please point out the discussion.
the "= =" in JS and the forced type conversion