1. ||:
首先在对于 a || b,大家都知道判断标准是只有当 a 为 false且 b 为 false时,整个语句为 假,否则为真。
因此,在 c = a ||b 中,只有当a 为 false 时才会考虑 b 的值,即:当 a 不为 false 时,等同于 c = a; 当 a 为 false 时,等同于 c = b;
2. &&:
对于 a && b. 判断标准为只有当 a 为 true 且 b 为 true 时,整个语句为真,其他的情况下整个语句为假。
因此,在 c = a && b中,只有当 a 为 true 时才会考虑 b 的值,即:当 a 为 true 时,等价于 c = b; 当a 为 false 时,等价于 c = a。
ps: 这里提及的 true 与 false 为转化为 Boolean 类型时,并非为简单的直接看其值为 true或false。
3. ?相关赋值运算
3.1 ?? 非空运算符
?? 运算符被称为非空运算符。如果第一个参数不是 null/undefined(这里只有这两个假值),将返回第一个参数,否则返回第二个参数。
console.log( undefined ?? 5); // 5
console.log( false ?? 5); // false
console.log( null ?? 5); // 5
console.log( NaN ?? 5); // NaN
console.log('' ?? 5); // ''
console.log( 0 ?? 5); // 0
3.2 ??= 空赋值运算符
??= 也被称为空赋值运算符,与 上面的非空运算符相关。联系如下:
var x = null
var y = 5
var z = undefined
console.log(x ??= y) // => 5
console.log('x',x)
console.log(z = (z ?? x)) // => 5
console.log('z',z)
3.3. ?. 链判断运算符
?. 被称为链判断运算符,用于在引用对象链中的属性值时,验证每个引用。当引用为空时,表达式停止计算并返回 undefined。
var obj = {
index: 1,
abcd: {
index: 2,
abc: {
index: 3,
ab: 10
}
}
}
console.log(obj.abcd.abc) // {index: 3, ab: 10}
console.log(obj.abcd.abc.ab) // 10
console.log(obj.abcd.abc?.bc) // undefined
4.3 ?: 三元运算符
?: 被称为 条件运算符,接受三个运算数:条件? 表达式1(条件为真时执行的表达式) : 表达式2(条件为假时执行的表达式)。
var flag = false
var value = flag ? '11' : '00'