javascript中的 ?. 、 ?? 、 ??=

96 阅读1分钟

可选链运算符(?.)

let a; 
let b = a.name; //报错 Uncaught TypeError: Cannot read properties of undefined (reading 'name')
let b = a?.name; //undefind

当a存在并且具有name属性时,就会将a.name的值赋值给b,否则就将undefined赋值给b,关键是a为空([null] 或者 [undefined])的情况下都不会引起错误。当我们尝试访问可能不存在的对象属性,可选链运算符将会使表达式更短、更简明。

访问数组也同样适用

let arr = [];
console.log(a[0]) //报错 Uncaught TypeError: Cannot read properties of undefined (reading '0')
console.log(a?.[0]) //undefined

空值合并运算符(??)

?? 是一个逻辑运算符,当左侧的操作数为null或者 undefined时,返回右侧操作数,否则返回左侧操作数。
与逻辑或运算符||的区别:逻辑或运算符会在左侧操作数为假值的时候返回右侧操作数。
假值:能够转化为 false 的值,例如 0、 空字符串''、null、undefined、NaN。
真值:能够转化为 true 的值。

let a;
let b = 1;
let c = 0;
console.log(a||b) //1
console.log(a??b) //1
console.log(c||b) //1
console.log(c??b) //0

逻辑空赋值(??=)

逻辑空赋值运算符(x ??= y)仅在 x 是空值(null 或 undefined)时对其赋值。

let a
let b = {name:'张三'}
let c = {name:'李四'}
a??=b
c??=b
console.log(a) //{name: '张三'} ,a空置,为其赋值
console.log(c)//{name: '李四'},c不为空,不会重新赋值