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

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

    In ECMAScript 6, the equivalent of ~~ is Math.trunc:

    Returns the integral part of a number by removing any fractional digits. It does not round any numbers.

    Math.trunc(13.37)   // 13
    Math.trunc(42.84)   // 42
    Math.trunc(0.123)   //  0
    Math.trunc(-0.123)  // -0
    Math.trunc("-1.123")// -1
    Math.trunc(NaN)     // NaN
    Math.trunc("foo")   // NaN
    Math.trunc()        // NaN
    

    The polyfill:

    function trunc(x) {
        return x < 0 ? Math.ceil(x) : Math.floor(x);
    }
    

提交回复
热议问题