Sao operation of JS

text

      The most notorious bug in js is 0.1 + 0.2 != 0.3, just like java, all floating-point operations are unsafe due to precision problems!

All people suggested not to use bit operations in js,

If the use of js is better, you can use the bit operation to improve the calculation performance. Okay, not too much, just cut into the topic:

 

1. Bit operation

Using the   <<   operator, you can quickly calculate an integer to the power of 2. If you write a decimal, it will automatically ignore the decimal

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

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

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

2. Use & to judge odd and even numbers

Odd & 1 = 1

Even & 1 = 0

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

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

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

3. Use!! to convert numbers to boolean values

!! The non-zero value is true, if it is 0, it is false

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

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

4. Use ~~, >>, <<, >>>>, | to round off quickly

Remove the decimal point directly. >>> Cannot round negative numbers 

//正数
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. Use ^ to quickly exchange values

Quickly swap the values ​​of two variables

//传统的方式 需要借助第三个临时变量完成
		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. Use ^ to determine whether the numbers are equal

let a = 1025;

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

7. n & (n - 1)If it is 0, it means that n is an integer power of 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

 

Easter eggs

Enter the following code in the console

(!(~+[])+{})[--[~+""][+[]]*[~+[]]+~~!+[]]+({}+[])[[~!+[]]*~+[]]

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_43619066/article/details/109255892
Sao