JavaScript 中是 true == 1 和 false == 0 吗?
我正在阅读一本关于 JavaScript 的好书.
I was reading a good book on JavaScript.
开头是:
布尔类型只接受两个字面值:真和假.它们与数值不同,所以 true 不等于 1,false 不等于 0.
Boolean type take only two literal values: true and false. These are distinct from numeric values, so true is not equal to 1, and false is not equal to 0.
但是,我观察到以下情况:
However, I observed following:
if(1==true)
document.write("oh!!! that's true"); //**this is displayed**
我知道,JavaScript 中的每种类型都有对应的布尔值.
I know, that every type in JavaScript has a Boolean equivalent.
但是,真相是什么?
推荐答案
确实 true
和 false
在 Javascript 中不代表任何数值.
It's true that true
and false
don't represent any numerical values in Javascript.
在某些语言(例如 C、VB)中,布尔值被定义为实际数值,因此它们只是 1 和 0(或 -1 和 0)的不同名称.
In some languages (e.g. C, VB), the boolean values are defined as actual numerical values, so they are just different names for 1 and 0 (or -1 and 0).
在其他一些语言(例如 Pascal、C#)中,有一种独特的布尔类型,它不是数字.可以在布尔值和数值之间进行转换,但不会自动发生.
In some other languages (e.g. Pascal, C#), there is a distinct boolean type that is not numerical. It's possible to convert between boolean values and numerical values, but it doesn't happen automatically.
Javascript 属于具有独特布尔类型的类别,但另一方面,Javascript 非常热衷于在不同数据类型之间转换值.
Javascript falls in the category that has a distinct boolean type, but on the other hand Javascript is quite keen to convert values between different data types.
例如,即使数字不是布尔值,您也可以在需要布尔值的地方使用数值.使用 if (1) {...}
和 if (true) {...}
一样有效.
For example, eventhough a number is not a boolean, you can use a numeric value where a boolean value is expected. Using if (1) {...}
works just as well as if (true) {...}
.
在比较值时,例如在您的示例中, ==
运算符和 ===
运算符之间存在差异.==
相等运算符很高兴地在类型之间进行转换以找到匹配项,因此 1 == true
的计算结果为 true,因为 true
被转换为 1代码>.
===
类型相等运算符不进行类型转换,因此 1 === true
计算结果为 false,因为值属于不同类型.
When comparing values, like in your example, there is a difference between the ==
operator and the ===
operator. The ==
equality operator happily converts between types to find a match, so 1 == true
evaluates to true because true
is converted to 1
. The ===
type equality operator doesn't do type conversions, so 1 === true
evaluates to false because the values are of different types.
相关文章