search

Home  >  Q&A  >  body text

JavaScript bitwise NOT operator (~)

See the lottery code for <TFC2017/>

~~23.5 // 23

Why can ~ operators round numbers?

伊谢尔伦伊谢尔伦2738 days ago1041

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-06-28 09:31:08

    via ToInt32. Its function is to flip the binary form of the operand bitwise. So two ~~ connected together are equivalent to the following operations:

    1. Perform ToInt32 on the operand

    2. Flip by bit

    3. Bitwise flipping again actually still uses the absolute value rounding of ToInt32

    In addition, there is a trick about the ~ operator that is quite practical: the value of ~(-1) is 0, and -1 is the only value that returns a false value after the ~ operation (including other ones Special values ​​such as NaN, {}, [], etc. will not return false values) If the indexOf function of strings and arrays fails to search, it will return -1. At this time, you can use if(~str.indexOf('str ')) // To indicate that
    is found is more elegant than judging >= 0 or != -1 , and it is similar to using !! to judge non-false values

    Author: mdluo
    Link: https://www.zhihu.com/questio...

    Rounding converts floating point numbers into 32-bit binary integers, so bit operations that can restore the state can be rounded, such as 23.5 >> 0 //23, 23.5 >> 0 //23 .

    reply
    0
  • Cancelreply