1. if 与多个 OR(||) 条件的简写
if (car === 'audi' || car === 'BMW' || car === 'Tesla') {
// code
}
在传统的方式中,我们曾经以上述模式编写代码。但是我们可以简单地使用数组并包含而不是使用多个 || 条件。看看下面的例子。
if (['audi', 'BMW', 'Tesla', 'grapes'].includes(car)) {
// code
}
2. if 与多个 And(&&) 条件的简写
if (obj && obj.tele && obj.tele.stdcode) {
console.log(obj.tele .stdcode)
}
使用可选链接 (?.) 替换此代码段。
console.log(obj?.tele?.stdcode);
3. 检查变量的空值、未定义值和空值的简写
if (name !== null || name !== undefined || name !== '') {
const second = name;
}
简单的方法是
const second = name || '';
4. switch case从多个选项中选择的简写
switch (number) {
case 1:
return 'Case one';
case 2:
return 'Case two';
default:
return;
}
使用对象
const data = {
1: 'Case one',
2: 'Case two'
}[num];
5. 单行函数的函数简写
function example(value) {
return 2 * value;
}
使用箭头函数
const example = (value) => 2 * value
6. 条件调用函数的简写
function height() {
console.log('height');
}
function width() {
console.log('width');
}
if (type === 'heigth') {
height();
} else {
width();
}
简单的方法
type === 'heigth' ? height() : width()
7. 使用 if 将默认值设置为变量的简写
if (amount === null) {
amount = 0;
}
if (value === undefined) {
value = 0;
}
console.log(amount); // 0
console.log(value); // 0
简单写法
console.log(amount || 0); // 0
console.log(value || 0); // 0