Javascript equality operators

允我心安 提交于 2020-01-30 08:32:11

问题


In David Flanagan's Javascript guide, there is a statement:

the == operator never attempts to convert its operands to boolean

So here I did a little test:

var a = false;
var b = ""; // empty string
a == b; //returns true

Looking at Abstract Equality Comparison Algorithm there is a point:

e. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.

How can x and y be both true if y is string data type (without conversion)?


回答1:


What happens under the hood is

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

Number(false) == ""

followed by

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

Number(false) == Number("") -> 0 == 0

How can x and y be both true if y is string data type (without conversion)?

They are not both true, but after type coercion their values are equal.

the == operator never attempts to convert its operands to boolean

And that is correct, if you check the comparison algorithm you will find that types are never implicitly casted to Boolean.

References:

  • 11.9.3 The Abstract Equality Comparison Algorithm
  • 9.3 ToNumber


来源:https://stackoverflow.com/questions/31888631/javascript-equality-operators

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