What does ~~ (“double tilde”) do in Javascript?

前端 未结 9 839
有刺的猬
有刺的猬 2020-11-22 17:16

I was checking out an online game physics library today and came across the ~~ operator. I know a single ~ is a bitwise NOT, would that make ~~ a NOT of a NOT, which would

9条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 17:42

    The first ~ operator forces the operand to an integer (possibly after coercing the value to a string or a boolean), then inverts the lowest 31 bits. Officially ECMAScript numbers are all floating-point, but some numbers are implemented as 31-bit integers in the SpiderMonkey engine.

    You can use it to turn a 1-element array into an integer. Floating-points are converted according to the C rule, ie. truncation of the fractional part.

    The second ~ operator then inverts the bits back, so you know that you will have an integer. This is not the same as coercing a value to boolean in a condition statement, because an empty object {} evaluates to true, whereas ~~{} evaluates to false.

    js>~~"yes"
    0
    js>~~3
    3
    js>~~"yes"
    0
    js>~~false
    0
    js>~~""
    0
    js>~~true
    1
    js>~~"3"
    3
    js>~~{}
    0
    js>~~{a:2}
    0
    js>~~[2]
    2
    js>~~[2,3]
    0
    js>~~{toString: function() {return 4}}
    4
    js>~~NaN
    0
    js>~~[4.5]
    4
    js>~~5.6
    5
    js>~~-5.6
    -5
    

提交回复
热议问题