js按位运算符~和~~的使用
2020-07-28 本文已影响0人
追梦_life
在leetcode刷题时,看到了~~的写法,于是网上查了资料,在这里记录一下。
~(按位非)
MDN给出的解释如下:
对每一个比特位执行非(NOT)操作。NOT a 结果为 a 的反转(即反码)。非操作的真值表:
a | NOT a |
---|---|
0 | 1 |
1 | 0 |
9 (base 10) = 00000000000000000000000000001001 (base 2)
--------------------------------
~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
对任一数值 x 进行按位非操作的结果为 -(x + 1)。例如,~5 结果为 -6。
console.log('~null: ', ~null); // => -1
console.log('~undefined: ', ~undefined); // => -1
console.log('~0: ', ~0); // => -1
console.log('~{}: ', ~{}); // => -1
console.log('~[]: ', ~[]); // => -1
console.log('~(1/0): ', ~(1/0)); // => -1
console.log('~false: ', ~false); // => -1
console.log('~true: ', ~true); // => -2
console.log('~1.2543: ', ~1.2543); // => -2
console.log('~4.9: ', ~4.9); // => -5
console.log('~(-2.999): ', ~(-2.999)); // => 1
与 indexOf 一起使用示例:
if(arr.indexOf(ele) > -1){...} //易读
// 现在可以这样判断,两者效率:
if(~arr.indexOf(ele)){...} //简洁
~~ (双非)
相当于对任一数值 x 进行-(-(x+1) + 1)操作。
console.log('~~null: ', ~~null); // => 0
console.log('~~undefined: ', ~~undefined); // => 0
console.log('~~0: ', ~~0); // => 0
console.log('~~{}: ', ~~{}); // => 0
console.log('~~[]: ', ~~[]); // => 0
console.log('~~(1/0): ', ~~(1/0)); // => 0
console.log('~~false: ', ~~false); // => 0
console.log('~~true: ', ~~true); // => 1
console.log('~~1.2543: ', ~~1.2543); // => 1
console.log('~~4.9: ', ~~4.9); // => 4
console.log('~~(-2.999): ', ~~(-2.999)); // => -2
对于浮点数,~~value可以代替parseInt(value),而且前者效率更高些。
parseInt(-2.99) //-2
~~(-2.99) //-2
测试
var time1 = +new Date();
var count = 5000000;
var ele = 1;
var arr = [1,2,4,5,2];
var h = 1.01;
console.time('parseInt');
for (var i = count; i > 0; i--) {
parseInt(h);
}
console.timeEnd('parseInt'); //84.385ms
console.time('~~');
for (var i = count; i>0; i--) {
~~h;
}
console.timeEnd('~~'); //13.386ms
console.time('arr.indexOf(ele) > -1');
for (var j = count; j>0; j--) {
arr.indexOf(ele) > -1;
}
console.timeEnd('arr.indexOf(ele) > -1'); //16.263ms
console.time('~arr.indexOf(ele)');
for (var i = count; i>0; i--) {
~arr.indexOf(ele);
}
参考链接:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators