js的 空值合并运算符(? ?)、空值赋值运算符(? ? =)、可选链(?.)

一、空值合并运算符(??)

let a
let b
let c = 0
let d = 'hello'

a = b ?? d
console.log(a) // a='hello'

a = c ?? d
console.log(a) // a=0

当 ?? 的左侧变量是undefined、null之外的任何值,a都会等于左侧变量的值,否则a等于右侧变量的值。

二、空值赋值运算符(??=)

let a
let b
let c = 0
let d = 'hello'

a ??= d
console.log(a) // a='hello'

c ??= d
console.log(c) // c=0

当 ??= 左侧变量的值为null或undefined时,才会将右侧变量的值赋值给左侧变量,否则不会进行赋值。

三、可选链(?.)

let a
let b
let c = { name: 'luffy' }
let d = 'hello'

a = b?.name
console.log(a) // a=undefined

a = c?.name
console.log(a) // a='luffy'

对于a = b?.name,只有当b存在,且b具有name属性的时候,才会把值赋给a,否则就将undefined赋值给a。重要的是,不管b是否存在,不会报错。

记录于2022-4-12

猜你喜欢

转载自blog.csdn.net/qq_40146789/article/details/124124768