简化 if true...else 条件表达式

less
复制代码
less
复制代码
// bad
if (x === "abc" || x === "def" || x === "ghi" || x === "jkl") {
     //logic
}
     
// better
if (["abc", "def", "ghi", "jkl"].includes(x)) { 
     //logic
}

2然后调用该数组的 include 方法。

1. 多条件 if 语句

将多个值放入一个数组中,然后调用该数组的 include 方法。

less
复制代码
less
复制代码
// bad
if (x === "abc" || x === "def" || x === "ghi" || x === "jkl") {
     //logic
}
     
// better
if (["abc", "def", "ghi", "jkl"].includes(x)) { 
     //logic
}

2. 简化 if true...else 条件表达式

1. 多条件 if 语句

将多个值放入一个数组中,然后调用该数组的 include 方法。

less
复制代码
less
复制代码
// bad
if (x === "abc" || x === "def" || x === "ghi" || x === "jkl") {
     //logic
}
     
// better
if (["abc", "def", "ghi", "jkl"].includes(x)) { 
     //logic
}

2. 简化 if true...else 条件表达式

2. 简化 if true...else 条件表达式

ini
复制代码
ini
复制代码
// bad
let test: boolean;
if (x > 100) {  
    test = true;
  } else {  
    test = false;
}

// better
let test = x > 10 ? true : false;

//or let test = x > 10;

console.log(test);

3. 假值(undefined, null, 0, false, NaN, empty string)检查

当我们创建一个新变量时,有时我们想

  前端面试题库 (面试必备)            推荐:★★★★★

地址:前端面试题库

猜你喜欢

转载自blog.csdn.net/weixin_42981560/article/details/131814947