javaScript位移运算符

位移运算符(~~)(<<)(>>)

位移运算符(~~)暂时还没弄明白原理,只知道怎么使用

   ~~true == 1
   ~!true ==-1
   
   ~~false == 0
   ~!false ==-2

   ~~"" == 0
   ~!"" == -2

   ~~[] == 0
   ~![] ==-1
 
  ~~undefined ==0
  ~!undefined == -2

  ~~null == 0
  ~!null == -2
   
  ~~"字符串"==0
  ~!"字符串"==-1
  
  ~~"123"==~~123==123
  ~!"123"==-1
  ~!123 ==-1
  
  console.log("~~true =="+~~true);
  console.log("~!true =="+~~!true);
  console.log("~~false =="+~~false);
  console.log("~!false=="+~!false);
  console.log('~~""=='+~~"");
  console.log('~!""=='+~!"");
  console.log("~~[]=="+~~[]);
  console.log("~![]=="+~![]);
  console.log("~~undefined=="+~~undefined);
  console.log("~!undefined=="+~!undefined);
  console.log("~~null=="+~~null);
  console.log("~!null=="+~!null);
  console.log('~~"字符串"=='+~~"字符串");
  console.log('~!"字符串"=='+~!"字符串");
  console.log('~~"123.9"=='+~~"123.9");
  console.log('~~123.9=='+~~123.9);
  console.log('~!"123"=='+~!"123");
  console.log('~!123=='+~!123);
   var i=~~"123"
   console.log(i+1);

运行结果

101140_yari_2897732.png

通过代码可以直白的看出,(~~)位运算符只有运算true和纯数字字符(大于0的 数字字符)时候返回值大于0,并且可以把数字字符串转换为number类型,并且只返回整数位

 

位移运算符(<<)(>>)就比较好理解一些了(<<)左移运算,(>>)右移运算

console.log(3<<2);
console.log(3>>2);

输出

103305_aXAr_2897732.png

简单的说就是把数值转换为二进制,(<<)向左移动两位,(>>)向右移动两位,然后再转换成十进制显示出来,列子(3<<2)可以简单理解为3乘以2的二次方,(3>>2)可以简单理解为3除以2的二次方,就是3/4,转换成十进制只返回整数位就是0;

 

位运算符的应用:

用法一:取整

使用(~~x、x>>0、x<<0)的方式取整

因为是操作符,取整效率要比parseInt(x,n)方法的效率要高一些,(x是字符串,n是进制)

但是超过限制位后取整会出错

console.log(~~999999999.9999);

输出

163206_3Crl_2897732.png

console.log(~~9999999999.9999);

输出

163315_C2nT_2897732.png

简单上理解就是整数位超过10位会造成精度丢失

而且与Math.floor()也是有区别的,例如对负数取整,位移运算符是先取整后再加符号

console.log(~~(-1.5) );

输出

163838_DJgQ_2897732.png

Math.floor()是向下取整

console.log(Math.floor(-1.5) );

输出

163928_Aw8j_2897732.png

结论:在自己对数值比较明确,并且不会超限的情况下可以使用位移运算符取整,位运算只在数字小于2^32-1的时候靠谱

用法二:关于 ~ 操作符比较实用的技巧

~(-1)返回值为0,并且-1是进过~运算唯一返回假值的数,字符串和数组indexOf()查找方法为找到的时候返回值是(-1)

if(~str.indexOf('str')) //找到了...

 

转载于:https://my.oschina.net/ThreeTiger/blog/904521

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值