3

在 javascript 中,波浪号运算符是按位 NOT 或补码,那么为什么以下内容不能按预期工作?

var x = true;
var tildeX = ~x;
var exclX = !x;


tildeX == exclX; // returns false
4

3 回答 3

9

原因是因为true相当于1, 并且当您对得到~的数字执行按位 NOT() 时。与 NOT 运算符 ( ) 结合时会产生 false (因为与 NOT 运算符结合时会产生 true 的唯一数字是)1-2!0

以下是一些您可能会感兴趣的信息

引用自链接:

按位注意任何数字 x 产生 -(x + 1)

于 2013-10-22T09:43:50.953 回答
1

~ is a bitwise operation:

~(true) = ~1 = 0b11111110 (with 8bit character)

! is boolean negation:

!(true) = !1 = 0b00000000

于 2013-10-22T09:43:07.130 回答
0

x is not a boolean type and therefore has a load of leading bits set to zero.

~x will convert all those leading bits to 1. Therefore it will be non-zero.

!x, on the other hand, is zero.

That's why tildeX == exclX compares false.

于 2013-10-22T09:43:16.760 回答