JS按位非运算符(~)及双非(~~)的使用

~x 理解为 -(x + 1)

  1. console.log('~null: ', ~null); // => -1
  2. console.log('~undefined: ', ~undefined); // => -1
  3. console.log('~0: ', ~0); // => -1
  4. console.log('~{}: ', ~{}); // => -1
  5. console.log('~[]: ', ~[]); // => -1
  6. console.log('~(1/0): ', ~(1/0)); // => -1
  7. console.log('~false: ', ~false); // => -1
  8. console.log('~true: ', ~true); // => -2
  9. console.log('~1.2543: ', ~1.2543); // => -2
  10. console.log('~4.9: ', ~4.9); // => -5
  11. console.log('~(-2.999): ', ~(-2.999)); // => 1

~~x 就为 -(-(x+1) + 1)

  1. console.log('~~null: ', ~~null); // => 0
  2. console.log('~~undefined: ', ~~undefined); // => 0
  3. console.log('~~0: ', ~~0); // => 0
  4. console.log('~~{}: ', ~~{}); // => 0
  5. console.log('~~[]: ', ~~[]); // => 0
  6. console.log('~~(1/0): ', ~~(1/0)); // => 0
  7. console.log('~~false: ', ~~false); // => 0
  8. console.log('~~true: ', ~~true); // => 1
  9. console.log('~~1.2543: ', ~~1.2543); // => 1
  10. console.log('~~4.9: ', ~~4.9); // => 4
  11. console.log('~~(-2.999): ', ~~(-2.999)); // => -2

~value 的使用

判断数值中是否有某元素时,以前这样判断:

  1. if(arr.indexOf(ele) > -1){...} //易读

现在可以这样判断,两者效率:

  1. if(~arr.indexOf(ele)){...} //简洁

~~value的使用

对于浮点数,~~value可以代替parseInt(value),而且前者效率更高些

  1. parseInt(-2.99) //-2 ~~(-2.99) //-2