js优化小技巧

1、含有多个条件的if语句

我们可以在数组中存储多个值,并且可以使用数组的 includes 方法。

//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}

 

2、对null、undefined、empty这些值的检查

我们创建一个新变量,有时候需要检查是否为 Null 或 Undefined。JavaScript 本身就有一种缩写法能实现这种功能。

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== '') {
    let test2 = test1;
}
// Shorthand
let test2 = test1 || '';

 

3、同时为多个变量赋值

当我们处理多个变量,并且需要对这些变量赋不同的值,这种缩写法很有用。

//Longhand 
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand 
let [test1, test2, test3] = [1, 2, 3];

 

4、隐式返回缩写法

使用箭头函数,我们可以直接得到函数执行结果,不需要写 return 语句。

//longhand
function calculate(diameter) {
  return Math.PI * diameter
}
//shorthand
calculate = diameter => (
  Math.PI * diameter;
)

 

5、十进制指数形式

// Longhand
for (var i = 0; i < 10000; i++) { ... }

// Shorthand
for (var i = 0; i < 1e4; i++) {

 

6、查询条件缩写法

如果我们要检查类型,并根据类型调用不同的函数,我们既可以使用多个 else if 语句,也可以使用 switch,除此之外,如果有缩写法,代码会是怎么样呢?

// Longhand
if (type === 'test1') {
  test1();
}
else if (type === 'test2') {
  test2();
}
else if (type === 'test3') {
  test3();
}
else if (type === 'test4') {
  test4();
} else {
  throw new Error('Invalid value ' + type);
}
// Shorthand
var types = {
  test1: test1,
  test2: test2,
  test3: test3,
  test4: test4
};
 
var func = types[type];
(!func) && throw new Error('Invalid value ' + type); func();
posted @ 2021-03-11 10:22  ltog  阅读(68)  评论(0编辑  收藏  举报