JS 的骚操作

189 阅读1分钟

正文

js中最臭名昭著的Bug就是 0.1 + 0.2 != 0.3 ,跟java一样,因为精度的问题,导致所有的浮点运算都是不安全的!

所有有人提出不要在js中使用位运算,

如果js的运用比较好的,可以使用一下位运算提升运算性能,好了,不多叭叭了, 直接切入主题:

1. 位运算

使用 << 运算符,可以快速运算出一个2的整形数的次方,如果写的是小数会自动忽略小数

1 << 2; //4 2的2次方

1 << 10 ;//1024 2的十次方

1 << 2.5 ;//4 还是2的2次方,后面是小数的话,会自动把小数去掉

2.使用 & 来判断 奇、偶数

奇数 & 1 = 1

偶数 & 1 = 0

//奇数
console.log(7 & 1); //1 

//偶数
console.log(10 & 1);

//小数 还是自动忽略小数,如果小数点前面是那么就会返回1,是偶数就返回0
console.log(6.5 & 1);//0

3.使用 !! 将数字转成布尔值

!! 非 0的值就是true,如果是0 就false

console.log(!!6);//true

console.log(!!0);//false

4.使用 ~~ 、>> 、<< 、>>> 、| 快速取整

直接将小数点后面的去掉。 >>> 不能对负数取整

//正数
console.log(~~12.7); //12

console.log(12.7>>0);//12

console.log(12.7<<0);//12

console.log(12.7>>>0);//12

console.log(12.7|0);//12

//负数
console.log(~~-12.7|0);//-12

5.使用 ^ 快速交换值

快速交换两个变量的值

//传统的方式 需要借助第三个临时变量完成
		let a= 1;
        let b=8;
        let c=1;
        c = b ;//c=8
        b = a ;//b=1
        a = c ;//a=8
        console.log(a)//8
        console.log(b)//1

//使用 ^ ,就不需要第三个临时变量来存值了
		let a = 1;
		let b = 8;
		a ^= b;
		b ^= a;
		a ^= b;
		console.log(a);//8
		console.log(b);//1

6.使用 ^ 来判断数字是否相等

let a = 1025;

//c常规判断
if(a != 1024){
    console.log("不相等")
}
//使用 ^ 判断
if(a ^ 1024){
    console.log("不相等")
}

7.n & (n - 1),如果为 0,说明 n 是 2 的整数幂

let h = 96;
h & (h-1)
64
let h = 56;
h & (h-1)
48
let h = 48;
h & (h-1)
32
let h = 32;
h & (h-1)
0