?. 运算符
作用:在一个变量可能为null、或者undefined的时候,恰巧我又需要访问这个变量的一个属性,则用?.,有值则返回对应的值,否则返回undefined
例:
const obj = {hh: 'xxx'}
let res = obj?.data?.list
console.log(res) // undefined
console.log(obj?.hh?.length) //3
console.log(obj?.hh) // xxx
?? 运算符
作用:当??左侧的值是null或undefined时,取??右侧的值
例:
image.png
image.png
var ibo = {}
console.log(ibo?.a ?? 111) // 111
var ibo = {a:{b:1}}
console.log(ibo?.a?.b ?? 111) //1
console.log(1??'2') // 1
console.log(null ?? "xx") // xx
console.log(undefined ?? "xx") // xx
console.log( ' '?? "xx") // 空值
??= 运算符
作用:当??左侧的值是null或undefined时,取??右侧变量的值赋值给左侧变量
例:
let b = '你好';
let a = 0
let c = null;
let d = ’123‘
b ??= a; // b = “你好”
c ??= d // c = '123'
测验题:
let a;
let b = "不知名前端"
let c = null;
let d = 0;
let e;
e ??= a?.b ?? c ?? d?.a ?? b;
console.log(e)
网友评论