Why does “true” == true show false in JavaScript?

∥☆過路亽.° 提交于 2019-11-26 04:21:17

问题


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:

  1. Are they of the same type? No
  2. Is either operand a number or boolean? Yes
  3. Can we convert both to a number? No (isNaN(Number(\"true\")) // true)
  4. Is either operand a string? Yes
  5. 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?


回答1:


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.




回答2:


== comparison operator defined in Ecma 5 as

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

So, "true" == true is interpreted by js engine as

  1. "true" == toNumber(true)
  2. "true" == 1
  3. toNumber("true") == 1
  4. NaN == 1

===> false




回答3:


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.



来源:https://stackoverflow.com/questions/11363659/why-does-true-true-show-false-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!