JavaScript bitwise NOT operator (~)
伊谢尔伦
伊谢尔伦 2017-06-28 09:29:08
0
1
1001

See the lottery code for <TFC2017/>

~~23.5 // 23

Why can ~ operators round numbers?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
伊谢尔伦

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 .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!