JS按位非运算符(~)及双非(~~)的使用
~x 理解为 -(x + 1)
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
~~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 的使用
判断数值中是否有某元素时,以前这样判断:
if(arr.indexOf(ele) > -1){...} //易读
现在可以这样判断,两者效率:
if(~arr.indexOf(ele)){...} //简洁
~~value的使用
对于浮点数,~~value可以代替parseInt(value),而且前者效率更高些
parseInt(-2.99) //-2 ~~(-2.99) //-2