Why does not the true match 'true' with double equals sign '==' in JavaScript? [duplicate]

耗尽温柔 提交于 2019-12-23 09:31:15

问题


This small portion of code took a long time to be noticed.

I thought if I do the following, it would be fine

if('true' == true) {
    alert("Does not happen");
}

But it does not pass the if condition.

I thought the double equals == matches the value not the type as matching the type is the job of ===.

Now my questions are why wasn'the true typecast to 'true' or why is it checking for the type of these operands?


回答1:


'true' == true

This is what happens here (according to the rules):

-- convert boolean to a number (rule 7):

'true' == 1

-- convert 'true' to Number (rule 5):

Number('true') == 1

-- Number('true') is NaN:

NaN == 1

-- return false (rule 1.c.i)

== is indeed confusing, but it makes some sense once you understand the rules:

  • garbage is equal to garbage (undefined == null)
  • no booleans (they're compared as numbers)
  • if one of the parts is a number, compare numeric
  • if one of the parts is a string, compare as strings
  • otherwise, a and b must be the same thing.



回答2:


The == of Javascript is one of the worst part of the language that is build under no comprehensible logic... We suffer an old spec, that's just the answer.

Take a loot at the complete Facepalm:

https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Sameness

edit for the edit

Yeah, the 'typecast' is not working as we could expect... there is no other answer.. :/




回答3:


See the rules for ==.

Type(x) is a string and Type(y) is a boolean. So Step 7 applies. It converts the boolean to a number and compares it to the string. The string you have won't match any number.




回答4:


in JavaScript boolean, The result is 1 if the argument is true. The result is +0 if the argument is false. So, 'true' == true is equivalent to 'true' == 1 which is of course, false.



来源:https://stackoverflow.com/questions/21041619/why-does-not-the-true-match-true-with-double-equals-sign-in-javascript

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