我今天在检查一个在线游戏物理库时遇到了~~操作员。我知道单个的~是一个按位的NOT,这会使~~变成一个NOT的NOT吗?它会返回相同的值,不是吗?


当前回答

波浪号(~)的算法为-(N+1)

考考:

~0 = -(0+1) = -1
~5 = -(5+1) = -6
~-7 = -(-7+1) = 6

双波浪号为-(-(N+1)+1)

例如:

~~5 = -(-(5+1)+1) = 5
~~-3 = -(-(-3+1)+1) = -3

三波浪号是-(-((N+1)+1)+1)

例如:

~~~2 = -(-(-(2+1)+1)+1) = -3
~~~3 = -(-(-(3+1)+1)+1) = -4

其他回答

将字符串转换为数字

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 = 0

if (~someStr.indexOf("a")) {
  // Found it
} else  {
  // Not Found
}

波浪号(~)的算法为-(N+1)

考考:

~0 = -(0+1) = -1
~5 = -(5+1) = -6
~-7 = -(-7+1) = 6

双波浪号为-(-(N+1)+1)

例如:

~~5 = -(-(5+1)+1) = 5
~~-3 = -(-(-3+1)+1) = -3

三波浪号是-(-((N+1)+1)+1)

例如:

~~~2 = -(-(-(2+1)+1)+1) = -3
~~~3 = -(-(-(3+1)+1)+1) = -4

只是提醒你一下。这里的其他答案给我带来了麻烦。

其目的是删除浮点数小数点后的任何内容,但它有一些极端情况,使其存在bug风险。我建议避免……

首先,~~对很大的数字不起作用。

~~1000000000000 == -727279968

作为替代方法,使用Math.trunc()(正如Gajus所提到的,Math.trunc()返回浮点数的整数部分,但仅在ECMAScript 6兼容的JavaScript中可用)。你可以为非ecmascript -6环境创建自己的Math.trunc():

如果(! Math.trunc) { 数学。Trunc =函数(值){ 返回Math.sign(值)* Math.floor(Math.abs(值)); } }

我为此写了一篇博客文章供参考:http://bitlords.blogspot.com/2016/08/the-double-tilde-x-technique-in.html

下面是一个如何有效使用这个操作符的例子,在使用它是有意义的地方:

leftOffset = -(~~$('html').css('padding-left').replace('px', '') + ~~$('body').css('margin-left').replace('px', '')),

来源:

参见与点交互部分

在ECMAScript 6中,等价的~~是Math.trunc:

通过删除任何小数,返回数字的整部分。它不会四舍五入任何数字。

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

polyfill:

function trunc(x) {
    return x < 0 ? Math.ceil(x) : Math.floor(x);
}