当前位置:网站首页>JS 问号?妙用
JS 问号?妙用
2022-08-04 18:36:00 【蓓蕾心晴】
// 1. ?
var obj ={a:1,b:2}
obj.c.a
// 会报错:Uncaught TypeError: Cannot read properties of undefined,因为obj.c 不存在
解决方法:
obj.c?.a
// 等价于
obj.c && obj.c.a
// ?是可选链操作符,在引用为空null 或者 undefined 的情况下不会引起错误,该表达式短路返回值是 undefined
// 2. ??
// 空值合并运算符,在ES2020中新增,可以用来保证值不为 null 或者 undefined
var a1="";
var b1=a1??"default1" // ""
var a2=undefined;
var b2=a2??"default2" // default2
var a3=null;
var b3=a3??"default3" // default3
// 注:(??) 直接和 AND(&&)和 OR(||)一起用会报错,如果要一起用,记得单独给 ?? 左右表达式加括号,如:
b=(a??"dffdfdf") || 123 // dffdfdf
b=(a??"dffdfdf") && 123 // 123
// 3. 逻辑或(||)
// 空值合并运算符将跳过 null,undefined
// 逻辑或运算符会跳过 null,undefined,false
false ?? 'hello' // false
false || 'hello' // 'hola'
// 如果不想用要虚值,可以使用 ||。如果只想检查是否为 null 或 undefined,就用 ??边栏推荐
猜你喜欢

ros2订阅esp32发布的电池电压数据-补充

2019 Haidian District Youth Programming Challenge Activity Elementary Group Rematch Test Questions Detailed Answers

基于3D机器视觉的采血试管分拣系统

通配符SSL证书不支持多域名吗?

The CPU suddenly soars and the system responds slowly, what is the cause?Is there any way to check?

Hezhou Cat1 4G module Air724UG is configured with RNDIS network card or PPP dial-up, and the development board is connected to the Internet through the RNDIS network card (taking the RV1126/1109 devel

Alibaba Cloud International Edition uses ROS to build WordPress tutorial

机器学习——线性回归

The upgrade of capacity helps the flow of computing power, the acceleration moment of China's digital economy

如何进行自动化测试?
随机推荐
EuROC 数据集格式及相关代码
mq消息积压怎么对应
如何进行自动化测试?
开篇-开启全新的.NET现代应用开发体验
Flask framework implementations registered encryption, a Flask enterprise class learning 】 【
July 31, 2022 Summary of the third week of summer vacation
部署LVS-DR群集
margin 塌陷和重合的理解
Win10只读文件夹怎么删除
ros2订阅esp32发布的电池电压数据
不论你是大众,科班和非科班,我这边整理很久,总结出的学习路线,还不快卷起来
开发那些事儿:如何通过EasyCVR平台获取监控现场的人流量统计数据?
ERC721标准与加密猫
敏捷开发项目管理的一些心得
Scala105-Spark.sql中collect_list用法
C#爬虫之通过Selenium获取浏览器请求响应结果
EasyCVR如何通过接口调用设备录像的倍速回放?
网站设计师:Nicepage 4.15 Crack By Xacker
【STM32】STM32单片机总目录
flink-cdc支持并行读取一张mysql表的binlog不?