How does !!~ (not not tilde/bang bang tilde) alter

2019-01-02 17:23发布

If you read the comments at the jQuery inArray page here, there's an interesting declaration:

!!~jQuery.inArray(elm, arr) 

Now, I believe a double-exclamation point will convert the result to type boolean, with the value of true. What I don't understand is what is the use of the tilde (~) operator in all of this?

var arr = ["one", "two", "three"];
if (jQuery.inArray("one", arr) > -1) { alert("Found"); }

Refactoring the if statement:

if (!!~jQuery.inArray("one", arr)) { alert("Found"); }

Breakdown:

jQuery.inArray("one", arr)     // 0
~jQuery.inArray("one", arr)    // -1 (why?)
!~jQuery.inArray("one", arr)   // false
!!~jQuery.inArray("one", arr)  // true

I also noticed that if I put the tilde in front, the result is -2.

~!!~jQuery.inArray("one", arr) // -2

I don't understand the purpose of the tilde here. Can someone please explain it or point me towards a resource?

13条回答
大哥的爱人
2楼-- · 2019-01-02 17:27

I assume, since it is a bitwise operation, it is the fastest (computationally cheap) way to check whether path appears in modifiedPaths.

查看更多
路过你的时光
3楼-- · 2019-01-02 17:28

The tilde operator isn't actually part of jQuery at all - it's a bitwise NOT operator in JavaScript itself.

See The Great Mystery of the Tilde(~).

You are getting strange numbers in your experiments because you are performing a bitwise logical operation on an integer (which, for all I know, may be stored as two's complement or something like that...)

Two's complement explains how to represent a number in binary. I think I was right.

查看更多
听够珍惜
4楼-- · 2019-01-02 17:33

My guess is that it is there because it's a few characters shorter (which library authors are always after). It also uses operations that only take a few machine cycles when compiled into the native code (as opposed to the comparison to a number.)

I agree with another answer that it's an overkill but perhaps might make sense in a tight loop (requires performance gain estimation, though, otherwise may turn out to be premature optimization.)

查看更多
流年柔荑漫光年
5楼-- · 2019-01-02 17:35

As (~(-1)) === 0, so:

!!(~(-1)) === Boolean(~(-1)) === Boolean(0) === false
查看更多
只若初见
6楼-- · 2019-01-02 17:36

The ~ operator is the bitwise NOT operator. What this means is that it takes a number in binary form and turns all zeroes into ones and ones into zeroes.

For instance, the number 0 in binary is 0000000, while -1 is 11111111. Likewise, 1 is 00000001 in binary, while -2 is 11111110.

查看更多
不再属于我。
7楼-- · 2019-01-02 17:37

The ~ for all 4 bytes int is equal to this formula -(N+1)

SO

~0   = -(0+1)   // -1
~35  = -(35+1)  // -36 
~-35 = -(-35+1) //34 
查看更多
登录 后发表回答