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. 简化 if true...else

对于不包含大逻辑的 if-else 条件,可以使用下面的快捷写法。我们可以简单地使用三元运算符来实现这种简化。

// Longhand
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}
// Shorthand
let test = (x > 10) ? true : false;
//or we can use directly
let test = x > 10;
console.log(test);

如果有嵌套的条件,可以这么做。

let x = 300,
test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';
console.log(test2); // "greater than 100"

3. 声明变量

当我们想要声明两个具有相同的值或相同类型的变量时,可以使用这种简写。

//Longhand 
let test1;
let test2 = 1;
//Shorthand 
let test1, test2 = 1;

4. null、undefined 和空值检查

当我们创建了新变量,有时候想要检查引用的变量是不是为非 null 或 undefined。JavaScript 确实有一个很好的快捷方式来实现这种检查。

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

5. null 检查和默认赋值

let test1 = null,
    test2 = test1 || '';
console.log("null check", test2); // output will be ""

6. undefined 检查和默认赋值

let test1 = undefined,
    test2 = test1 || '';
console.log("undefined check", test2); // output will be ""

一般值检查

let test1 = 'test',
    test2 = test1 || '';
console.log(test2); // output: 'test'

另外,对于上述的 4、5、6 点,都可以使用?? 操作符。

如果左边值为 null 或 undefined,就返回右边的值。默认情况下,它将返回左边的值。

const test= null ?? 'default';
console.log(test);
// expected output: "default"
const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值