JavaScript相等运算符 [英] Javascript equality operators
问题描述
在David Flanagan的Javascript指南中,有一条语句:
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
查看抽象平等比较算法有一个重点:
e。如果Type(x)为布尔值,则如果x和y均为true或均为false,则返回true。否则,返回false。
e. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.
如果y是字符串数据类型(不进行转换),则x和y都如何为真?
How can x and y be both true if y is string data type (without conversion)?
推荐答案
内幕发生的事情是
如果
Type(x)
是Boolean
,则返回比较结果ToNumber(x) == y
。
If
Type(x)
isBoolean
, return the result of the comparisonToNumber(x) == y
.
Number(false) == ""
其后是
如果
Type(x)
是Number
和Type(y)
是String
,返回比较结果x == ToNumber(y)
。
If
Type(x)
isNumber
andType(y)
isString
, return the result of the comparisonx == ToNumber(y)
.
Number(false) == Number("") -> 0 == 0
如果y,x和y都为真是字符串数据类型(不转换)?
How can x and y be both true if y is string data type (without conversion)?
它们都不都是 true
,但是在强制类型之后它们的值相等。
They are not both true
, but after type coercion their values are equal.
==运算符从不尝试将其操作数转换为布尔值
the == operator never attempts to convert its operands to boolean
这是正确的,如果检查比较算法,您会发现类型永远不会隐式转换为 Boolean
。
And that is correct, if you check the comparison algorithm you will find that types are never implicitly casted to Boolean
.
引用:
- 11.9.3 The Abstract Equality Comparison Algorithm
- 9.3 ToNumber
这篇关于JavaScript相等运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!