What exactly does ~ do?

This question already has an answer here:

  • What does a tilde do when it precedes an expression? 6 answers

  • It's the bitwise NOT operator. It will convert the operand to an 32-bit integer, then yields one's complement (inverts every bit) of that integer.

    Finally, ! will return true if and only only if the result of that operation is 0 .

    Some examples might help:

      x |   x (bin) | ~x (bin)  |  ~x |   !~x
     -3 | 1111…1101 | 0000…0010 |   2 | false
     -2 | 1111…1110 | 0000…0001 |   1 | false
     -1 | 1111…1111 | 0000…0000 |   0 |  true
      0 | 0000…0000 | 1111…1111 |  -1 | false
      1 | 0000…0001 | 1111…1110 |  -2 | false
    

    In other words,

    if ( !~text.indexOf('a') ) { }
    

    is equivalent to:

    if ( text.indexOf('a') == -1 ) { }
    

    ~ is the bitwise negation operator[MDN]. It converts its operand to a 32-bit integer and swaps all the 1 s to 0 s and all the 0 s to 1 s.

    For example:

    0000 0000 0000 0000 0000 0000 0000 0000 = 0
    1111 1111 1111 1111 1111 1111 1111 1111 = ~0 = -1
    

    Instead of doing text.indexOf(str) !== -1) you can use the tricky !~text.indexOf(str) , because ~1 === 0 and !0 === true .


    ~ is the unary negation operator. Basically converts the operand to a 32-bit integer and then flips every bit of the integer.

    ~12 =
    ~(00000000 00000000 00000000 00001100) =
     (11111111 11111111 11111111 11110011) =
    -13
    
    链接地址: http://www.djcxy.com/p/75046.html

    上一篇: 〜[Array] .indexOf(key)做什么?

    下一篇: 到底做什么?