P粉3365367062023-08-24 09:01:58
==
operator (Equal ) true == 1; //true, because 'true' is converted to 1 and then compared "2" == 2; //true, because "2" is converted to 2 and then compared
===
operator(Identity)true === 1; //false "2" === 2; //false
This is because the equality operator ==
does a type cast , which means the interpreter will implicitly try to convert the value before comparing.
On the other hand, the identity operator ===
does not do type coercion and therefore does not convert the value when comparing.
P粉1788942352023-08-24 00:58:02
The strict equality operator (===
) behaves the same as the abstract equality operator (==
), except that no type conversion is performed and the types must be the same. considered equal.
Reference:JavaScript Tutorial: Comparison Operators
==
The operator will compare for equality after any necessary type conversions. ===
The operator does not perform a conversion, so if the two values are not of the same type, ===
will simply return false
. Both are equally fast.
Quoting Douglas Crockford’s wonderful JavaScript: The Good Parts一个>,
@Casebash in the comments and @Phillipe Laybaert's answer about objects. For objects, ==
and ===
behave identically to each other (except in special cases).
var a = [1,2,3]; var b = [1,2,3]; var c = { x: 1, y: 2 }; var d = { x: 1, y: 2 }; var e = "text"; var f = "te" + "xt"; a == b // false a === b // false c == d // false c === d // false e == f // true e === f // true
The special case is when you compare a primitive to an object that evaluates to the same primitive, due to its toString
or valueOf
method. For example, consider comparing a string primitive to a string object created using the String
constructor.
"abc" == new String("abc") // true "abc" === new String("abc") // false
Here==
operator checks the value of both objects and returns true
, but ===
sees that they are of different types and returns false
. Which one is correct? It really depends on what you're comparing. My suggestion is to bypass this problem entirely and just don't use the String
constructor to create a string object from a string literal.
refer to
https://262.ecma-international.org/5.1/#sec-11.9 .3