逻辑运算符:“||”
背景: 当我们创建一个新变量时,有时我们想检查引用的变量是否是一个假值,例如 null 或 undefined 或空字符串。JavaScript 确实为这种检查提供了一个很好的快捷方式——逻辑 OR 运算符 (||)
原理: “||” 仅当左侧为空或 NaN 或 null 或 undefined 或 false 时,如果左侧操作数为假,则将返回右侧操作数,逻辑或运算符 ( || ) 将返回右侧的值。
## 1.赋值:
//** bad**
if (test1 !== null || test1 !== undefined || test1 !== "") {
let test2 = test1;
}
// **better**
let test2 = test1 || "";
**2.逻辑判断:**
// bad
if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// better
if (test1){
// do some
}else{
// do other
}
***//Note: If test1 has a value, the logic after if will be executed. *
*//This operator is mainly used for null, undefined, and empty string checks.***