1. 使用左移运算符 <<
迅速得出2的次方
1 << 2 // 4, 即 2的2次方
1 << 10 // 1024, 即 2的10次方
// 但是要注意使用场景
a = 2e9; // 2000000000
a << 1; // -294967296
2. 使用 ^
切换变量 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
//注意 >>> 不可对负数取整 取出来的值会为0
6. 使用^
来检查数字是否不相等
// --- before ---
if (a !== 1171) {...};
// --- after ---
if (a ^ 1171) {...};
7. 使用toString(16)
取随机字符串
Math.random().toString(16).substring(2, 15);
//.substring() 的第二个参数控制取多少位 (最多可取13位)
8. 使用 split(0)
使用数字来做为 split 的分隔条件可以节省2字节
// --- before ---
"alpha,bravo,charlie".split(",");
// --- after ---
"alpha0bravo0charlie".split(0);
9. 使用.link()
创建链接
// --- before ---
let b = `<a herf="www.google.com">google</a>`;
// --- after ---
let b = google .link( www.google.com );
10. 使用 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"
11. 使用 Array.length = 0
来清空数组
12. 使用 Array.slice(0)
实现数组浅拷贝
13. 使用 !+"1"
快速判断 IE8 以下的浏览器