Sometimes you will see three equal signs (===) used when judging whether two objects are equal. What is the difference between it and two equal signs (==)? Woolen cloth? To put it simply, when using "==", if the types of both sides are different, the js engine will convert them into the same type and then compare them, while "===" will not perform type conversion, so when the two sides do not belong to the same Type, definitely not equal. For example:
var a = 0, b = '0'; alert((a == b) + '--' + (a === b))
The result seen at this time is "true–false".
=== Judgment rules
If the types are different, [not equal]
If both are numerical values , and are the same value, then [equal]; (!Exception) is that if at least one of them is NaN, then [not equal]. (To determine whether a value is NaN, you can only use isNaN() to determine)
If both are strings and the characters at each position are the same, then [equal]; Otherwise [not equal].
If both values are true, or both are false, then [equal].
If two values refer to the same object or function, then [equal]; otherwise [not equal].
If both values are null, or both are undefined, then [equal].
== Judgment rules:
If the two value types are the same, perform === comparison.
If two value types are different, they may be equal. Perform type conversion and then compare according to the following rules:
If one is null and the other is undefined, then [equal].
If one is a string and the other is a numerical value, convert the string into a numerical value and then compare.
If any value is true, convert it to 1 and compare; if any value is false, convert it to 0 and compare.
If one is an object and the other is a numeric value or string, convert the object into a value of the basic type and then compare. The object is converted to the base type using its toString or valueOf method. JS core built-in classes will try valueOf before toString; the exception is Date, which uses toString conversion. Non-js core objects, let's say (it's more troublesome, I don't quite understand)
Any other combination is [not equal].
Special attention needs to be paid to the conversion of true and false, for example:
alert(true == 1); //ture alert(true == 2); //false, true会转换成number,也就是1,当然 1 不等于 2 //可以使用 !! 来把一个数据类型转换为boolean型 alert(true == !!2) //true,!2 === false !(!=2) = !false = true
In addition, in js, if a variable is used in a logical operation, then the variable is When there is no initial value or its value is 0, -0, null, "", false, undefined or NaN, its value is false. Otherwise, its value is true.
The above is the detailed content of Compare the usage differences between == and ===. For more information, please follow other related articles on the PHP Chinese website!