为什么 ~ operator returns -1 用于 Javascript 中的函数?
Why ~ operator returns -1 for a function in Javascript?
~(function () {}).toString();
是绝对有效的 JavaScript 语法,我看到它 returns -1
.
我知道 ~
不是运算符。例如 ~5
=~0101
表示以 2 为基数的 1010
和十进制的 10
。
console.log(~(function () {}).toString());
但是这种情况怎么解释呢?
也许 ~NaN
returns -1
.
摘自this blog: The Great Mystery of the Tilde(~):
波浪号是一个运算符,可以执行您通常认为没有任何目的的操作。它是一个一元运算符,将表达式放在它的右边,对其执行这个小算法(其中 N
是波浪号右边的表达式):-(N+1)
。请参阅下面的一些示例。
console.log(~-2); // 1
console.log(~-1); // 0
console.log(~0); // -1
console.log(~1); // -2
console.log(~2); // -3
根据spec
Let oldValue be ToInt32(GetValue(expr)).
Number((function () {}).toString();)
-> Number("function () {}")
-> NaN
再次按照 spec
If number is NaN, +0, −0, +∞, or −∞, return +0.
所以 ~NaN
等于 ~0
即 -1
~(function () {}).toString();
是绝对有效的 JavaScript 语法,我看到它 returns -1
.
我知道 ~
不是运算符。例如 ~5
=~0101
表示以 2 为基数的 1010
和十进制的 10
。
console.log(~(function () {}).toString());
但是这种情况怎么解释呢?
也许 ~NaN
returns -1
.
摘自this blog: The Great Mystery of the Tilde(~):
波浪号是一个运算符,可以执行您通常认为没有任何目的的操作。它是一个一元运算符,将表达式放在它的右边,对其执行这个小算法(其中 N
是波浪号右边的表达式):-(N+1)
。请参阅下面的一些示例。
console.log(~-2); // 1
console.log(~-1); // 0
console.log(~0); // -1
console.log(~1); // -2
console.log(~2); // -3
根据spec
Let oldValue be ToInt32(GetValue(expr)).
Number((function () {}).toString();)
-> Number("function () {}")
-> NaN
再次按照 spec
If number is NaN, +0, −0, +∞, or −∞, return +0.
所以 ~NaN
等于 ~0
即 -1