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

前端 未结 9 513
有刺的猬
有刺的猬 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:38

    Just a bit of a warning. The other answers here got me into some trouble.

    The intent is to remove anything after the decimal point of a floating point number, but it has some corner cases that make it a bug hazard. I'd recommend avoiding ~~.

    First, ~~ doesn't work on very large numbers.

    ~~1000000000000 == -727279968

    As an alternative, use Math.trunc() (as Gajus mentioned, Math.trunc() returns the integer part of a floating point number but is only available in ECMAScript 6 compliant JavaScript). You can always make your own Math.trunc() for non-ECMAScript-6 environments by doing this:

    if(!Math.trunc){
        Math.trunc = function(value){
            return Math.sign(value) * Math.floor(Math.abs(value));
        }
    }

    I wrote a blog post on this for reference: http://bitlords.blogspot.com/2016/08/the-double-tilde-x-technique-in.html

提交回复
热议问题