1. 程式人生 > >javascript奇淫技巧

javascript奇淫技巧

asc pan 位移 ole [0 logs rpi () 布爾

1. 取整同時轉成數值型:

1     console.log("10.340"|0);    //10
2     console.log("10.560"^0);    //10
3     console.log(-2.25|0);       //-2
4     console.log(~~-2.25);       //-2

2.日期轉數值:

    var d = +new Date();        //1499149610813

3. 隨機碼:

1 Math.random().toString(16).substring(2);        //14位:adfe8d8800e04
2 Math.random().toString(36).substring(2);        //11位:yc290rtrpij

4.交換值:

1 a= [b, b=a][0];

5.條件判斷:

 1     var a = b && 1;
 2     //相當於
 3     if (b) {
 4         a = 1;
 5     }
 6 
 7     var a = b || 1;
 8     //相當於
 9     if (b) a = b;
10     else a = 1;

6.清空數組:

1     arr.length=0;        //設置數組長度清空數組

7.強制取Boolean值:

1 var a="";
2 !!a;            //雙感嘆號才能真正的將變量轉換成對應的Boolean值,第一個感嘆號是將其轉化成Boolean類型的值,但是這一操作得到的是其取反以後的值,再進行一次取反運算才能得到其對應真正的布爾值

8.位移符的應用:

1 var num = 10 >> 1; // 相當於10 / 2,但是效率更高 
2 console.log(num) // 5;
3 
4 var num = 2 << 3; // 2的四次方
5 console.log(num) // 16;

javascript奇淫技巧