我今天在检查一个在线游戏物理库时遇到了~~操作员。我知道单个的~是一个按位的NOT,这会使~~变成一个NOT的NOT吗?它会返回相同的值,不是吗?
当前回答
只是提醒你一下。这里的其他答案给我带来了麻烦。
其目的是删除浮点数小数点后的任何内容,但它有一些极端情况,使其存在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
其他回答
波浪号(~)的算法为-(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
在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);
}
只是提醒你一下。这里的其他答案给我带来了麻烦。
其目的是删除浮点数小数点后的任何内容,但它有一些极端情况,使其存在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
}
源
除了截断实数外,~~还可以用作更新对象中的计数器的操作符。应用于未定义的对象属性的~~将解析为零,如果该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;