Is true == 1 and false == 0 in JavaScript?(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.
这篇关于JavaScript 中是 true == 1 和 false == 0 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript 中是 true == 1 和 false == 0 吗?


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01