admin管理员组

文章数量:1391794

I am looking at SocketIO source code and it has this statement:

if (-~manager.get('blacklist').indexOf(packet.name)) {

What does -~ shorthand mean here?

I am looking at SocketIO source code and it has this statement:

if (-~manager.get('blacklist').indexOf(packet.name)) {

What does -~ shorthand mean here?

Share Improve this question edited Mar 5, 2017 at 0:19 user1106925 asked May 17, 2013 at 16:53 mvbl fstmvbl fst 5,2739 gold badges45 silver badges59 bronze badges 1
  • 4 It's not a "shorthand", it's two operators in a row (- and ~). – JJJ Commented May 17, 2013 at 16:56
Add a ment  | 

3 Answers 3

Reset to default 4

It is appears to be a trick for:

if(manager.get('blacklist').indexOf(packet.name) !== -1)

As mentioned by others ~ is bitwise negation which will flip the binary digits. 00000001 bees 11111110 for example, or in hexidecimal, 0x01 bees 0xFE.

-1 as a signed int 32 which is what all bitwise operators return (other than >>> which returns a unsigned int 32) is represented in hex as 0xFFFFFFFF. ~(-1) flips the bits to result in 0x00000000 which is 0.

The minus simply numerically negates the number. As zzzBov mentioned, in this case it does nothing.

-~(-1) === 0

And

~(-1) === 0

The code could be changed to:

if(~manager.get('blacklist').indexOf(packet.name))

But, in my opinion, characters aren't at such a premium so the longer version, which is arguably a bit more readable, would be better, or implementing a contains method would be even better, this version is best left to a JavaScript piler or pressor to perform this optimization.

Bitwise inversion.

~0 == 0xFFFFFFFF == -1
~1 == 0xFFFFFFFE

Minus is arithmetic inversion. So result is 0 if indexOf failed (return -1)

The two operators are not a shorthand form of anything. ~ is bitwise negation, and - is standard negation.

~foo.indexOf(bar) is a mon shorthand for foo.contains(bar). Because the result is used in an if statement, the - sign immediately after is pletely useless and does nothing of consequence.

-~ together is a means to add 1 to a number. It's generally not useful, and would be better expressed as + 1, unless you're peting in a code golf where you're not allowed to use the digit 1

本文标签: javascriptWhat doesbefore indexOf() meanStack Overflow