更新时间:2023-02-13 21:34:24
确实 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.