Why "~undefined" is
This question already has an answer here:
~
is bitwise NOT. It uses ToInt32
to convert the argument to a number. ToInt32
is defined as:
...
In turn, ToNumber(undefined)
returns NaN
, so according to step 3, ToInt32
returns 0
.
And ~0
is -1
.
every thing that cannot be represented in bits in JS for example "undefined, NaN" is treated a 0
or 0000000000000b
for the ~
operator since it converts the operand into an signed integer see @felixkling answer for more details on this and since the operation ~
is BITwise not or 1s complement which flips the bits so the statement results in 111111111111b
as a sequence of 1
and when dealing in numbers on binary level the MSB(most significant bit) is treated as a sign
so when converting all the 0s
to 1s
it results in decimal value of -1
try ~0
for instance. and use this code to get the binary representation of a number (-3 >>> 0).toString(2))
Apparently the bit representation of undefined
is all 0
s. This can be seen if by the following: undefined | 0
undefined | 0
which evaluates to 0
. Because of this we know that undefined
's bit representation is all zeros.
If we now filp all bits (wich is exactly what ~
does) we get all 1
s which is the representation of -1
.
All this works because of javascript's type cohersion
链接地址: http://www.djcxy.com/p/75040.html下一篇: 为什么“〜undefined”是