可选链(.?)
相信大家应该都写过类似的代码:
let arr = res && res.data && res.data.list
可选链写法
let arr = res?.data?.list
总结 可选链 这种写法就是防止报错 判断值是否为null或者undefined
空值合并运算符??
console.log(1 || "xx") //1
console.log(0 || "xx") //xx
console.log(null || "xx") //xx
console.log(undefined || "xx") //xx
console.log(-1 || "xx") //-1
console.log("" || "xx") //xx
console.log(1 ?? "xx") //1
console.log(0 ?? "xx") //0
console.log(null ?? "xx") //xx
console.log(undefined ?? "xx") //xx
console.log(-1 ?? "xx") //-1
console.log("" ?? "xx") //''
//可以看到 当第一个值不等于null 或 undefined 就会打印第一个值 0、false、""这些都会被??忽略
空值赋值运算符(??=)
let b = '你好';
let a = 0
let c = null;
let d = '123'
b ??= a; // b = “你好”
c ??= d // c = '123'
当??=左侧的值为null、undefined的时候,才会将右侧变量的值赋值给左侧变量.其他所有值都不会进行赋值.同样在一些场景下,可以省略很多代码.
扩展知识
let a;
let b = "不知名前端"
let c = null;
let d = 0;
let e;
e ??= a?.b ?? c ?? d?.a ?? b;
console.log(e)
你就说看着头大不大叭~
最后
这种语法低版本浏览器可能不兼容。谨慎使用!
使用频繁可能会头疼~
当然-你也别问我是怎么知道的
我听我朋友说的~