为什么在Javascript中 "1" == 1 返回true?

5

我想了解更多关于这种自由语言的知识,一个好的解释会很棒。

谢谢!


请查看比较运算符 - Xotic750
1
请参见https://dev59.com/MXVD5IYBdhLWcg3wHn2d。 - Onyxite
请参阅:http://docs.nodejitsu.com/articles/javascript-conventions/what-are-truthy-and-falsy-values - Velmurugan S
将数字"1"转换为数字类型,然后进行检查,结果总是为真。 - Velmurugan S
1
我正在努力学习更多。如果您想详细了解事情,请查看规范http://es5.github.io。 - Paul S.
5个回答

7

来自规范

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:

  1. 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 is0, return true.
    
    v. If x is0 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.

  2. If x is null and y is undefined, return true.

  3. If x is undefined and y is null, return true.

  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).

  5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.

  6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.

  7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).

  8. If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).

  9. If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.

  10. Return false.


5

隐式检查

"1" == 1 //true
1 == 1 //true

显式检查

1 === 1 //true
"1" === 1 //false

4
这是因为JavaScript只比较语句中的值"1" == 1。双等号告诉JavaScript,即使类型不同,也允许强制转换和比较纯值。
这就是为什么经常建议使用三个等号符号,以避免这种类型强制转换。三个等号符号仅纯粹地比较值。

2

答案:

由于缺少类型检查

等于(==)如果两个操作数的类型不相同,JavaScript会将操作数转换后再进行严格比较。如果任一操作数是数字或布尔值,则会尽可能地将操作数转换为数字;否则,如果任一操作数是字符串,则会尽可能地将字符串操作数转换为数字。如果两个操作数都是对象,则JavaScript会比较内部引用,当操作数在内存中指向同一个对象时,它们是相等的。

因此,始终使用===运算符或使用strict mode

JavaScript 运算符


1
如果你使用 == 符号,JavaScript 将不会检查类型。它会自动进行类型转换。
如果你使用 ===,JavaScript 也会检查类型。对于你的例子,这将返回 false。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接