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