JavaScript中的空值合并操作符【??】和可选链操作符【?.】的理解和使用

参考:http://t.csdn.cn/5700Y

?? - 空值合并操作符

结构:eg: let res = num01??num02;
?? 当左侧的变量为null或undefined的时,返回左侧num02否则返回自身num01(num01相当于null和undefined下兜底作用)

let res01 = null ?? "B站"; // 'B站'
let res02 = undefined ?? "P站"; // 'P站'
let res03 = "P站" ?? "B站"; // 'P站'

?. - 可选链操作符

结构:eg: obj.userInfo?.name;
?. 当访问链深处属性值的时候不必明确验证链中所方法对象的有效性

使用场景

场景01 - 可选链与函数调用

let result = someInterface.customMethod?.();
注:如果存在一个属性名且不是函数, 使用 ?. 仍然会产生一个 TypeError 异常 (x.y is not a function).

场景02 - 使用空值合并操作符

let customer = {
name: "Carl",
details: { age: 82 }
};
let customerCity = customer?.city ?? "P站";
console.log(customerCity); // “P站”

场景03 - 短路计算

let a = null;
let x = 0;
let prop = a?.[x++];
console.log(x); // x 将不会被递增,依旧输出 0
posted @   Felix_Openmind  阅读(133)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}
点击右上角即可分享
微信分享提示