~~(“双波浪号”)在 Javascript 中有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4055633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does ~~ ("double tilde") do in Javascript?
提问by Shane Tomlinson
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 give back the same value, wouldn't it?
我今天正在查看一个在线游戏物理库,并遇到了 ~~ 运算符。我知道单个 ~ 是按位非,这会使 ~~ 不是非的非,它会返回相同的值,不是吗?
回答by PleaseStand
It removes everything after the decimal point because the bitwise operators implicitly convert their operands to signed 32-bit integers. This works whether the operands are (floating-point) numbers or strings, and the result is a number.
它删除小数点后的所有内容,因为按位运算符将其操作数隐式转换为有符号的 32 位整数。无论操作数是(浮点)数字还是字符串,这都适用,结果是数字。
In other words, it yields:
换句话说,它产生:
function(x) {
if(x < 0) return Math.ceil(x);
else return Math.floor(x);
}
only if xis between -(231) and 231- 1. Otherwise, overflow will occur and the number will "wrap around".
仅当x介于 -(2 31) 和 2 31- 1 之间时。否则,将发生溢出并且数字将“环绕”。
This may be considered useful to convert a function's string argument to a number, but both because of the possibility of overflow and that it is incorrect for use with non-integers, I would not use it that way except for "code golf" (i.e.pointlessly trimming bytes off the source code of your program at the expense of readability and robustness). I would use +x
or Number(x)
instead.
这可能被认为对将函数的字符串参数转换为数字很有用,但由于可能发生溢出以及与非整数一起使用是不正确的,我不会以这种方式使用它,除了“代码高尔夫”(即以牺牲可读性和健壮性为代价,从程序的源代码中毫无意义地修剪字节)。我会用+x
orNumber(x)
代替。
How this is the NOT of the NOT
这不是 NOT 的 NOT
The number -43.2, for example is:
例如,数字 -43.2 是:
-43.210= 111111111111111111111111110101012
-43.2 10= 111111111111111111111111111010101 2
as a signed (two's complement) 32-bit binary number. (JavaScript ignores what is after the decimal point.) Inverting the bits gives:
作为有符号(二进制补码)的 32 位二进制数。(JavaScript 忽略小数点后的内容。)反转位给出:
NOT -4310= 000000000000000000000000001010102= 4210
非 -43 10= 00000000000000000000000000101010 2= 42 10
Inverting again gives:
再次反转给出:
NOT 4210= 111111111111111111111111110101012= -4310
不是 42 10= 111111111111111111111111111010101 2= -43 10
This differs from Math.floor(-43.2)
in that negative numbers are rounded toward zero, not away from it. (The floor function, which would equal -44, always rounds down to the next lower integer, regardless of whether the number is positive or negative.)
这不同于Math.floor(-43.2)
负数向零舍入,而不是远离它。(floor 函数等于 -44,总是向下舍入到下一个较小的整数,无论数字是正数还是负数。)
回答by Shanti
The first ~ operator forces the operand to an integer (possibly after coercing the value to a string or a boolean), then inverts the lowest 31 bits. Officially ECMAScript numbers are all floating-point, but some numbers are implemented as 31-bit integers in the SpiderMonkey engine.
第一个 ~ 运算符强制操作数为整数(可能在将值强制为字符串或布尔值之后),然后反转最低 31 位。官方 ECMAScript 数字都是浮点数,但有些数字在 SpiderMonkey 引擎中实现为 31 位整数。
You can use it to turn a 1-element array into an integer. Floating-points are converted according to the C rule, ie. truncation of the fractional part.
您可以使用它将 1 元素数组转换为整数。浮点数根据 C 规则进行转换,即。截断小数部分。
The second ~ operator then inverts the bits back, so you know that you will have an integer. This is not the same as coercing a value to boolean in a condition statement, because an empty object {} evaluates to true, whereas ~~{} evaluates to false.
第二个 ~ 运算符然后将位反转,因此您知道您将拥有一个整数。这与在条件语句中将值强制为布尔值不同,因为空对象 {} 的计算结果为 true,而 ~~{} 的计算结果为 false。
js>~~"yes"
0
js>~~3
3
js>~~"yes"
0
js>~~false
0
js>~~""
0
js>~~true
1
js>~~"3"
3
js>~~{}
0
js>~~{a:2}
0
js>~~[2]
2
js>~~[2,3]
0
js>~~{toString: function() {return 4}}
4
js>~~NaN
0
js>~~[4.5]
4
js>~~5.6
5
js>~~-5.6
-5
回答by Gajus
In ECMAScript 6, the equivalent of ~~
is Math.trunc:
ECMAScript中6中,相当于~~
是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);
}
回答by Richard Marskell - Drackir
The ~
seems to do -(N+1)
. So ~2 == -(2 + 1) == -3
If you do it again on -3 it turns it back: ~-3 == -(-3 + 1) == 2
It probably just converts a string to a number in a round-about way.
在~
似乎做-(N+1)
。因此,~2 == -(2 + 1) == -3
如果您在 -3 上再次执行此操作,则会将其返回:~-3 == -(-3 + 1) == 2
它可能只是以一种迂回的方式将字符串转换为数字。
See this thread: http://www.sitepoint.com/forums/showthread.php?t=663275
请参阅此线程:http: //www.sitepoint.com/forums/showthread.php?t= 663275
Also, more detailed info is available here: http://dreaminginjavascript.wordpress.com/2008/07/04/28/
此外,这里提供更详细的信息:http: //dreaminginjavascript.wordpress.com/2008/07/04/28/
回答by James Sumners
Given ~N
is -(N+1)
, ~~N
is then -(-(N+1) + 1)
. Which, evidently, leads to a neat trick.
给定~N
是-(N+1)
,~~N
则是-(-(N+1) + 1)
。显然,这导致了一个巧妙的技巧。
回答by JSideris
Just a bit of a warning. The other answers here got me into some trouble.
只是一点警告。这里的其他答案让我遇到了一些麻烦。
The intent is to remove anything after the decimal point of a floating point number, but it has some corner cases that make it a bug hazard. I'd recommend avoiding ~~.
目的是删除浮点数小数点后的任何内容,但它有一些极端情况使其成为错误风险。我建议避免~~。
First, ~~ doesn't work on very large numbers.
首先,~~ 不适用于非常大的数字。
~~1000000000000 == -727279968
~~1000000000000 == -727279968
As an alternative, use Math.trunc()
(as Gajus mentioned, Math.trunc()
returns the integer part of a floating point number but is only available in ECMAScript 6 compliant JavaScript). You can always make your own Math.trunc()
for non-ECMAScript-6 environments by doing this:
作为替代方案,使用Math.trunc()
(如 Gajus 所述,Math.trunc()
返回浮点数的整数部分,但仅在符合 ECMAScript 6 的 JavaScript 中可用)。您始终可以Math.trunc()
通过执行以下操作为非 ECMAScript-6 环境创建自己的环境:
if(!Math.trunc){
Math.trunc = function(value){
return Math.sign(value) * Math.floor(Math.abs(value));
}
}
I wrote a blog post on this for reference: http://bitlords.blogspot.com/2016/08/the-double-tilde-x-technique-in.html
我写了一篇关于此的博客文章以供参考:http: //bitlords.blogspot.com/2016/08/the-double-tilde-x-technique-in.html
回答by CroMagnon
Tilde(~) has an algorihm -(N+1)
波浪号(~) 有一个算法 -(N+1)
For examle:
例如:
~0 = -(0+1) = -1
~5 = -(5+1) = -6
~-7 = -(-7+1) = 6
Double tilde is -(-(N+1)+1)
双波浪号是 -(-(N+1)+1)
For example:
例如:
~~5 = -(-(5+1)+1) = 5
~~-3 = -(-(-3+1)+1) = -3
Triple tilde is -(-(-(N+1)+1)+1)
三重波浪号是 -(-(-(N+1)+1)+1)
For example:
例如:
~~~2 = -(-(-(2+1)+1)+1) = -3
~~~3 = -(-(-(3+1)+1)+1) = -4
回答by Mykhaylo Adamovych
Converting Strings to Numbers
将字符串转换为数字
console.log(~~-1); // -1
console.log(~~0); // 0
console.log(~~1); // 1
console.log(~~"-1"); // -1
console.log(~~"0"); // 0
console.log(~~"1"); // 1
console.log(~~true); // 1
console.log(~~false); // 0
~-1 is 0
~-1 是 0
if (~someStr.indexOf("a")) {
// Found it
} else {
// Not Found
}
回答by cssyphus
Here is an example of how this operator can be used efficiently, where it makes sense to use it:
下面是一个如何有效使用此运算符的示例,其中使用它是有意义的:
leftOffset = -(~~$('html').css('padding-left').replace('px', '') + ~~$('body').css('margin-left').replace('px', '')),
Source:
来源: