Why does "true" == true show false in JavaScript?

MDC describes the == operator as follows:

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.

With this in mind, I would evaluate "true" == true as follows:

  • Are they of the same type? No
  • Is either operand a number or boolean? Yes
  • Can we convert both to a number? No ( isNaN(Number("true")) // true )
  • Is either operand a string? Yes
  • Can we convert the other operand to a string? Yes ( String(true) === "true" // true )
  • I've ended up with the strings "true" and "true" , which should evaluate to true , but JavaScript shows false.

    What have I missed?


    Because "true" is converted to NaN , while true is converted to 1 . So they differ.

    Like you reported, both are converted to numbers, because at least true can be (see Erik Reppen's comment), and then compared.


    == comparison operator defined in Ecma 5 as

  • 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,
  • 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).
  • So, "true" == true is interpreted by js engine as

  • "true" == toNumber(true)
  • "true" == 1
  • toNumber("true") == 1
  • NaN == 1
  • ===> false


    Acording to The Abstract Equality Comparison Algorithm

    http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

    if one of the oprends is a boolean and other is not, boolean is converter to number 0 or 1. so true == "true" is false.

    链接地址: http://www.djcxy.com/p/72864.html

    上一篇: JavaScript数组的布尔评估

    下一篇: 为什么“true”== true在JavaScript中显示false?