位移运算符(~~)(<<)(>>)
位移运算符(~~)暂时还没弄明白原理,只知道怎么使用
~~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);
运行结果
通过代码可以直白的看出,(~~)位运算符只有运算true和纯数字字符(大于0的 数字字符)时候返回值大于0,并且可以把数字字符串转换为number类型,并且只返回整数位
位移运算符(<<)(>>)就比较好理解一些了(<<)左移运算,(>>)右移运算
console.log(3<<2);
console.log(3>>2);
输出
简单的说就是把数值转换为二进制,(<<)向左移动两位,(>>)向右移动两位,然后再转换成十进制显示出来,列子(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);
输出
console.log(~~9999999999.9999);
输出
简单上理解就是整数位超过10位会造成精度丢失
而且与Math.floor()也是有区别的,例如对负数取整,位移运算符是先取整后再加符号
console.log(~~(-1.5) );
输出
Math.floor()是向下取整
console.log(Math.floor(-1.5) );
输出
结论:在自己对数值比较明确,并且不会超限的情况下可以使用位移运算符取整,位运算只在数字小于2^32-1的时候靠谱
用法二:关于 ~ 操作符比较实用的技巧
~(-1)返回值为0,并且-1是进过~运算唯一返回假值的数,字符串和数组indexOf()查找方法为找到的时候返回值是(-1)
if(~str.indexOf('str')) //找到了...