JavaScript中是真的== 1和假= = 0? [英] Is true == 1 and false == 0 in JavaScript?
问题描述
我正在读一本关于JavaScript的好书。
I was reading a good book on JavaScript.
它始于:
布尔类型只取两个文字值:true和假。这些与数值不同,因此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.
但是,我观察到以下:
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.
例如,虽然数字不是布尔值,但您可以使用布尔值为的数值预期。使用如果(1){...}
与一样,如果(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.
这篇关于JavaScript中是真的== 1和假= = 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!