我今天在检查一个在线游戏物理库时遇到了~~操作员。我知道单个的~是一个按位的NOT,这会使~~变成一个NOT的NOT吗?它会返回相同的值,不是吗?
当前回答
~似乎是-(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/
其他回答
将字符串转换为数字
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;
下面是一个如何有效使用这个操作符的例子,在使用它是有意义的地方:
leftOffset = -(~~$('html').css('padding-left').replace('px', '') + ~~$('body').css('margin-left').replace('px', '')),
来源:
参见与点交互部分
~~可以用作Math.trunc()的简写
~~8.29 //输出8
Math.trunc(8.29) //输出
波浪号(~)的算法为-(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