~~

  • 用于数字取整
  • undefined null NaN 都会变成 0
    1
    console.log(~~(11.11));     // 11

&

  • 判断奇偶
  • undefined null NaN “” 都会变成 0
    1
    2
    console.log(7 & 1);    // 1
    console.log(8 & 1) ; // 0

!!

  • 转换布尔值
  • undefined null NaN 0 “”都会变成 false
  • [] {} 会变成 true
    1
    2
    3
    4
    5
    console.log(!!7);               // true
    console.log(!![]); // true
    console.log(!!{}); // true
    console.log(!!null); // false
    console.log(!!undefined); // false

>>

  • 左位移一等于乘二
  • 右位移一等于除二
  • undefined null NaN “” 都会变成 0
    1
    2
    console.log(16 >> 1);      // 8
    console.log(16 << 1); // 32

清空数组

1
2
3
let arr = [1];
arr.length = 0;
console.log(arr); // []

生成随机数

1
2
3
0 | Math.random() * 100
new Date % 100 //两位随机数
new Date % 1000 //三位随机数

生成随机字符串

1
2
// .substring() 的第二个参数控制取多少位 (最多可取13位)
Math.random().toString(16).substring(2, 15);

创建链接

1
console.log("Google".link("www.google.com")); // <a href="www.google.com">Google</a>

快速判断IE8以下的浏览器

1
2
var isIE8 = !+"1";
console.log(isIE8); // false // Chrome 87

正确处理异常的方法

1
2
3
4
5
try {
// something
} catch (e) {
window.location.href = "http://stackoverflow.com/search?q=[js]+" + e.message;
}

参考