- 使用左移运算符 << 迅速得出2的次方
1 << 2// 4, 即 2的2次方
1 << 10// 1024, 即 2的10次方
// 但是要注意使用场景
a = 2e9; // 2000000000
a << 1; // -294967296
- 使用 ^ 切换变量 0 或 1
// --- before ---
// if 判断
if (toggle) {
toggle = 0;
} else {
toggle = 1;
}
// 三目运算符
togle = toggle ? 0 : 1;
// --- after ---
toggle ^= 1;
3.使用 & 判断奇偶性
偶数 & 1 = 0
奇数 & 1 = 1
console.log(7 & 1); // 1
console.log(8 & 1) ; // 0
4.使用 !! 将数字转为布尔值
所有非0的值都是true,包括负数、浮点数:
console.log(!!7); // true
console.log(!!0); // false
console.log(!!-1); // true
console.log(!!0.71); // true
5.使用~、>>、<<、>>>、|来取整
相当于使用了 Math.floor()
console.log(~~11.71) // 11
console.log(11.71 >> 0) // 11
console.log(11.71 << 0) // 11
console.log(11.71 | 0) // 11
console.log(11.71 >>> 0) // 11
注意 >>> 不可对负数取整
6.使用^来完成值交换
这个符号的用法前面提到过,下面介绍一些高级的用法,在 ES6 的解构赋值出来之前,用这种方式会更快(但必须是整数):
// --- before ---
let temp = a; a = b; b = temp; // 传统,但需要借助临时变量
b = [a, a = b][0] // 借助数组
// --- after ---
let a = 7
let b = 1
a ^= b
b ^= a
a ^= b
console.log(a) // 1
console.log(b) // 7
[a, b] = [b, a]; // ES6,解构赋值
7使用 Array 来重复字符
// --- before ---
for (let a = "", i = 7; i--;) a+= 0;
// --- after ---
let b = Array(7).join(0); // "0000000"let c = Array(7).join( La ) // "LaLaLaLaLaLa"
// ES6
let d = "0".repeat(7); // "0000000"
8.使用.link() 创建链接
一个鲜为人知的方法,可以快速创建 a 标签
// --- before ---
let b = `<a herf="www.google.com">google</a>`;
// --- after ---
let b = google .link( www.google.com );