js运算符 ?. 、?? 、??= 解释说明
?. 可选链运算符,检查每个级别,如果碰到的是 undefined 或 null 属性,直接返回 undefined,不会继续往下检查
1 2 3 4 5 6 7 8 9
| const obj = {a: 0, b: 1}
console.log(obj.c)
console.log(obj?.c)
console.log(obj.c.d)
console.log(obj.c?.d)
|
?? 空值合并运算符,仅在 左侧 是 nullish (null 或 undefined) 时,使用右侧的值
1 2 3 4 5 6 7
| const obj = {a: 0, b: 1}
const n1 = obj.a || 1 console.log(n1)
const n2 = obj.a ?? 1 console.log(n2)
|
1 2 3 4 5
| const b1 = false || 1 console.log(b1)
const b2 = false ?? 1 console.log(b2)
|
1 2 3 4 5
| const u1 = undefined || 1 console.log(u1)
const u1 = undefined ?? 1 console.log(u2)
|
1 2 3 4 5
| const l1 = null || 1 console.log(l1)
const l2 = null ?? 1 console.log(l2)
|
??= 逻辑空赋值运算符 (x ??= y) 仅在 x 是 nullish (null 或 undefined) 时对其赋值
1 2 3 4 5 6 7 8 9 10 11 12 13
| const obj = {a: 0, b: false}
obj.a ??= 2 console.log(obj.a)
obj.b ??= 2 console.log(obj.b)
obj.c ??= 2 console.log(obj.c)
obj.c ??= 3 console.log(obj.c)
|