2021JavaScript 优化技巧
2021-04-21 本文已影响0人
浅忆_0810
2021JS优化技巧
1. switch
对应的缩写法
// Longhand
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
// Shorthand
var data = {
1: test1,
2: test2,
3: test
};
data[something] && data[something]();
2. 十进制数的指数形式
// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) { ... }
3. 字符串转换为数字
// Longhand
let test1 = parseInt('123');
let test2 = parseFloat('12.3');
// Shorthand
let test1 = +'123';
let test2 = +'12.3';
4. 按位非和 indexOf
缩写法
我们以查找特定值为目的迭代一个数组,通常用到 indexOf()
方法
// longhand
if(arr.indexOf(item) > -1) { // item found
}
if(arr.indexOf(item) === -1) { // item not found
}
// shorthand
if(~arr.indexOf(item)) { // item found
}
if(!~arr.indexOf(item)) { // item not found
}
对除 -1
外的任何数进行 按位非(~)
运算都会返回真值。把按位非的结果再次进行逻辑取反就是 !~
,这非常简单。或者我们也可以使用 includes()
函数
if (arr.includes(item)) {
// true if the item found
}
5. 两个位运算符缩写
两个按位非运算符只适用于
32
位整型
// Longhand
Math.floor(1.9) === 1 // true
// Shorthand
~~1.9 === 1 // true
6. 幂运算的缩写法
// longhand
Math.pow(2,3); // 8
// shorthand
2**3 // 8