What is the "double tilde" (~~) operator in JavaScript?

This question already has an answer here:

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

  • That ~~ is a double NOT bitwise operator.

    It is used as a faster substitute for Math.floor() .


    It hides the intention of the code.

    It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, ie converting the value to an integer number.

    Some use it as a faster alternative to Math.floor , but the speed difference is not that dramatic, and in most cases it's just micro optimisation. Unless you have a piece of code that really needs to be optimised, you should use code that descibes what it does instead of code that uses a side effect of a non-operation.

    Update 2011-08:

    With optimisation of the JavaScript engine in browsers, the performance for operators and functions change. With current browsers, using ~~ instead of Math.floor is somewhat faster in some browsers, and not faster at all in some browsers. If you really need that extra bit of performance, you would need to write different optimised code for each browser.

    See: tilde vs floor


    ~(5.5)   // => -6
    ~(-6)    // => 5
    ~~5.5    // => 5  (same as Math.floor(5.5))
    ~~(-5.5) // => -5 (NOT the same as Math.floor(-5.5), which would give -6 )
    

    For more info, see:

  • http://dreaminginjavascript.wordpress.com/2008/07/04/28/
  • 链接地址: http://www.djcxy.com/p/17722.html

    上一篇: 在Objective中生成随机数字

    下一篇: 什么是JavaScript中的“double tilde”(~~)运算符?