为什么JavaScript中的null大于-1,小于1,但不等于(==)为0?究竟是什么呢?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了为什么JavaScript中的null大于-1,小于1,但不等于(==)为0?究竟是什么呢?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2362字,纯文字阅读大概需要4分钟。
内容图文
![为什么JavaScript中的null大于-1,小于1,但不等于(==)为0?究竟是什么呢?](/upload/InfoBanner/zyjiaocheng/711/bf3508efd4f9432689e509dbf9eb095e.jpg)
来自Google Chrome控制台:
var x = null;
undefined
x > 0
false
x < 0
false
x > -1
true
x < 1
true
x == 1
false
x === 1
false
解决方法:
将null的相等性与0进行比较时,结果为false.如果强制在数字上下文中解释null,则将其视为0,结果为true.
你可以通过放在前面,或使用像<,< =,>和> =这样的数字运算符强制它成为数字.注意null> = 0和null< = 0都是真的.
> null == 0
false
> +null == 0
true
> null >= 0
true
> null <= 0
true
ECMAScript Language Specification定义何时执行所谓的“ToNumber”转换.如果是,则null和false都转换为0.
07001:
Table 14 — To Number Conversions
06001
知道何时应用ToNumber转换取决于所涉及的运算符.对于关系运算符<,< =,>和> =请参阅:
07002:
The comparison
x < y
, where x and y are values, produces true, false,
or undefined (which indicates that at least one operand is NaN). Such
a comparison is performed as follows:
Call ToPrimitive(x, hint Number).
Call ToPrimitive(y, hint Number).
If Type(Result(1)) is String and Type(Result(2)) is String, go to step 16. (Note that this step differs from step 7 in the algorithm for
the addition operator + in using and instead of or.)Call ToNumber(Result(1)).
Call ToNumber(Result(2)).
==运算符是不同的.其类型转换如下所述.注意null和false如何遵循不同的规则.
07003
The comparison x == y, where x and y are values, produces true or
false. Such a comparison is performed as follows:1. If Type(x) is different from Type(y), go to step 14.
…
14. If x is null and y is undefined, return true.
15. If x is undefined and y is null, return true.
16. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
17. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
18. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
19. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
20. If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
21. If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
22. Return false.
如果仔细阅读,可以看到为什么false == 0为true但null == 0为false.
>对于false == 0,Type(x)是布尔值.这意味着应用了步骤18的类型转换,并将false转换为数字. ToNumber(false)为0,0 == 0为真,因此比较成功.
>对于null == 0,Type(x)为Null.没有类型检查匹配,因此比较将进入步骤22,返回false.比较失败.
内容总结
以上是互联网集市为您收集整理的为什么JavaScript中的null大于-1,小于1,但不等于(==)为0?究竟是什么呢?全部内容,希望文章能够帮你解决为什么JavaScript中的null大于-1,小于1,但不等于(==)为0?究竟是什么呢?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。