我想了解更多关于这种自由语言的知识,一个好的解释会很棒。
谢谢!
我想了解更多关于这种自由语言的知识,一个好的解释会很棒。
谢谢!
来自规范
The Abstract Equality Comparison Algorithm
The comparison x == y, where x and y are values, produces true or false. Such a comparison is performed as follows:
If Type(x) is the same as Type(y), then
a. If Type(x) is Undefined, return true.
b. If Type(x) is Null, return true.
c. If Type(x) is Number, then
i. If x is NaN, return false. ii. If y is NaN, return false. iii. If x is the same Number value as y, return true. iv. If x is +0 and y is −0, return true. v. If x is −0 and y is +0, return true. vi. Return false.
d. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.
e. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.
f. Return true if x and y refer to the same object. Otherwise, return false.
If x is null and y is undefined, return true.
If x is undefined and y is null, return true.
If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
Return false.
隐式检查
"1" == 1 //true
1 == 1 //true
显式检查
1 === 1 //true
"1" === 1 //false
"1" == 1
。双等号告诉JavaScript,即使类型不同,也允许强制转换和比较纯值。答案:
由于缺少类型检查
等于(==)如果两个操作数的类型不相同,JavaScript会将操作数转换后再进行严格比较。如果任一操作数是数字或布尔值,则会尽可能地将操作数转换为数字;否则,如果任一操作数是字符串,则会尽可能地将字符串操作数转换为数字。如果两个操作数都是对象,则JavaScript会比较内部引用,当操作数在内存中指向同一个对象时,它们是相等的。
因此,始终使用===
运算符或使用strict mode