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


当前回答

在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);
}

其他回答

~似乎是-(N+1)。所以~2 == -(2 + 1)== -3如果你在-3上再做一次,它会把它转回来:~-3 == -(-3 + 1)== 2它可能只是以迂回的方式将字符串转换为数字。

请看这个帖子:http://www.sitepoint.com/forums/showthread.php?t=663275

此外,更详细的信息可在这里:http://dreaminginjavascript.wordpress.com/2008/07/04/28/

与Math.abs(Math.trunc(-0.123))相同,如果您想确保-也被删除。

除了截断实数外,~~还可以用作更新对象中的计数器的操作符。应用于未定义的对象属性的~~将解析为零,如果该counter属性已经存在,则将解析为相同的整数,然后再增加该整数。

let words=["abc", "a", "b", "b", "bc", "a", "b"];
let wordCounts={};    
words.forEach( word => wordCounts[word] = ~~wordCounts[word] + 1 );
console.log("b count == " + wordCounts["b"]);  // 3

下面两个赋值是等价的。

wordCounts[word] = (wordCounts[word] ? wordCounts[word] : 0) + 1;
wordCounts[word] = ~~wordCounts[word] + 1;

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

其目的是删除浮点数小数点后的任何内容,但它有一些极端情况,使其存在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

将字符串转换为数字

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
}