Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

精读《null >= 0?》 #36

Closed
ascoders opened this issue Sep 16, 2017 · 5 comments
Closed

精读《null >= 0?》 #36

ascoders opened this issue Sep 16, 2017 · 5 comments

Comments

@ascoders
Copy link
Owner

本期精读的文章是:null >= 0

看来大于等于号在 js 的执行逻辑并不符合直觉。

@linhuiw
Copy link
Contributor

linhuiw commented Sep 22, 2017

按文中说的,

if null < 0 is false, then null >= 0 is true; 

那可以理解 为什么 null >= 0 了.
同理 {} >= {} 也是 true;

{} < {} // false
{} >= {} // true

可是那为啥

null == {} // false
null < {} // false
null >= {} //false

image

@ascoders
Copy link
Owner Author

ascoders commented Sep 22, 2017

@linhuiw js 作判断时,首先在两个值上调用 ToPrimitive coercion,如果两个调用的结果都不是 string,就会对两个值进行 ToNumber 强转为 number,然后进行数值比较。

if null < 0 is false, then null >= 0 is true;

null >= 0 // is null < 0 ?
+null < 0 // => 0 < 0 => false, so null >= 0 is true

让我们看一下为什么 null >= [] === true?

null >= [] // is null < []? => 将右边转换为 0 => 将 null 转换为 0 => 0 < 0 显然是 false
// so null >= [] === true

Tip: 感谢 @mrcooder 的提示,此处答案已修正

再看看 null >= [1] 呢?答案是 false,最终会进行 0 < 1 的比较,因此反过来就是 false。

至于下面的情况:

null >= {} is false;

[] '' '0' false 强转 ToNumber 后值为 0,而 Number({}) 的结果为 NaN

null >= {} // is null < {} => is null < NaN => is 0 < NaN === false
// so null >= {} === true?

正常来看 null >= {} 结果应该是 true,但结果却是 false。我估计因为 NaN 在 js 中是个特殊的存在,所以直接判定为 false,而没有进行反转判断。

@ascoders
Copy link
Owner Author

当比较两边类型不同时,先做类型转换,当类型相同时,如果是 >= 判断,会转成 < 判断。而 NaN 会无视类型转换直接给出 false 结果,因此很可能跳过了 < 判断。

@LeeYunhang
Copy link

@ascoders 说的不错,但是有点问题,[] 是转换成 "" 而不是 "0";对于允许隐式转换的比较操作,只要一个操作数是 NaN,那么这个表达式一定返回 false。

这是隐式转换表

@realwugang
Copy link

学习了。

@ascoders ascoders mentioned this issue Oct 9, 2017
65 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants