简体   繁体   中英

Meaning of ~ in javascript function

I'm reading this javascript function:

if (~['bacon', 'burger'].indexOf(type)) {
    this.res.writeHead(200, { 'Content-Type': 'text/plain' });
    this.res.end('Serving ' + type + ' sandwich!\n');
  }

But I'm not sure what means ~ some one know when I use it or what meaning?

~ is the bitwise NOT operator. It toggles every bit of a number.

  • 0 becomes -1 .
  • -1 becomes 0 .
  • No other numbers become zero.

That means that

if (~['bacon', 'burger'].indexOf(type)) {

is a confusing way of writing

if (['bacon', 'burger'].indexOf(type) == -1) {

indexOf returns -1 when it doesn't find the string.

~ is a Bitwise NOT operator...

阅读更多

In this instance, the ~ allows that code to turn the return value of .indexOf() — which is a number indicating the position of the searched-for value in the array — into a boolean. In other words, it takes the "where is the value" result and turns it into a "is the value in the list" result.

How? Well, .indexOf() returns -1 when the value is not found, and a number greater than or equal to zero if it is. The ~ operator converts its numeric argument to a 32-bit integer and then inverts every bit. That process happens to turn -1 to 0 , and any positive integer to some negative non-zero value, and 0 to -1 . When such results are subsequently examined as boolean values, the original -1 will be false (because 0 is "falsy") while the integers greater than or equal to zero will be true (because they're all converted to some non-zero value).

Bitwise NOT (~ a) Inverts the bits of its operand.

EXAMPLE

  • 9 (base 10) = 00000000000000000000000000001001 (base 2)

      -------------------------------- 
  • ~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM