~
is a bitwise operator that flips all bits in its operand.
(~
是按位运算符 ,可翻转其操作数中的所有位。)
For example, if your number was 1
, its binary representation of the IEEE 754 float (how JavaScript treats numbers) would be...
(例如,如果您的数字为1
,则其对IEEE 754浮点数 (JavaScript如何处理数字)的二进制表示为...)
0011 1111 1111 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
So ~
converts its operand to a 32 bit integer (bitwise operators in JavaScript do that)...
(所以~
将其操作数转换为32位整数(JavaScript中的按位运算符会执行此操作)...)
0000 0000 0000 0000 0000 0000 0000 0001
If it were a negative number, it'd be stored in 2's complement: invert all bits and add 1.
(如果它是负数,则将以2的补码存储:将所有位取反并加1。)
...and then flips all its bits...
(...然后翻转所有位...)
1111 1111 1111 1111 1111 1111 1111 1110
So what is the use of it, then?
(那么,它的用途是什么?)
When might one ever use it?(什么时候可以使用它?)
It has a quite a few uses.
(它有很多用途。)
If you're writing low level stuff, it's handy.(如果您正在写低级的东西,这很方便。)
If you profiled your application and found a bottleneck, it could be made more performant by using bitwise tricks (as one possible tool in a much bigger bag).(如果您对应用程序进行了概要分析并发现了瓶颈,则可以通过使用按位技巧(作为更大的包装中的一种可能的工具)来提高性能。)
It's also a (generally) unclear trick to turn indexOf()
's found return value into truthy (while making not found as falsy ) and people often use it for its side effect of truncating numbers to 32 bits (and dropping its decimal place by doubling it, effectively the same as Math.floor()
for positive numbers).
(这也是一个(一般) 招不清楚打开indexOf()
的发现返回值放入truthy(同时使未找到为falsy),人们常常用它来截断数字为32位(通过丢弃其小数代替其副作用加倍,与正数实际上与Math.floor()
相同)。)
I say unclear because it's not immediately obvious what it is being used for.
(我说不清楚,因为目前尚不清楚它的用途。)
Generally, you want your code to communicate clearly to other people reading it.(通常,您希望您的代码与阅读它的其他人清楚地交流。)
While using ~
may look cool , it's generally too clever for its own good.(虽然使用~
可能看起来很酷 ,但出于自身利益通常太聪明了。)
:)(:))
It's also less relevant now that JavaScript has Array.prototype.includes()
and String.prototype.includes()
.
(现在,JavaScript具有Array.prototype.includes()
和String.prototype.includes()
也不再重要。)
These return a boolean value.(这些返回布尔值。)
If your target platform(s) support it, you should prefer this for testing for the existence of a value in a string or array.(如果您的目标平台支持它,则应首选此方法来测试字符串或数组中是否存在值。)