当前位置:网站首页>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,就用 ??
边栏推荐
- Nintendo won't launch any new hardware until March 2023, report says
- LVS+NAT 负载均衡群集,NAT模式部署
- The upgrade of capacity helps the flow of computing power, the acceleration moment of China's digital economy
- unity中实现ue眼球的渲染
- 机器学习——线性回归
- 猜数字游戏
- 股票开户广发证券,网上开户安全吗?
- Google Earth Engine APP - one-click online viewing of global images from 1984 to this year and loading an image analysis at the same time
- 力扣学习---0804
- asp dotnet core 通过图片统计 csdn 用户访问
猜你喜欢
[Distributed Advanced] Let's fill in those pits in Redis distributed locks.
unity中实现ue眼球的渲染
如何进行自动化测试?【Eolink分享】
【AI+医疗】斯坦福大学最新博士论文《深度学习在医学影像理解中的应用》,205页pdf
LVS负载均衡群集之原理叙述
Develop those things: How to obtain the traffic statistics of the monitoring site through the EasyCVR platform?
2022 May 1 Mathematical Modeling Question C Explanation
【软件工程之美 - 专栏笔记】37 | 遇到线上故障,你和高手的差距在哪里?
How does EasyCVR call the double-speed playback of device recording through the interface?
EasyCVR本地接入国标设备映射公网后,本地设备出现无法播放与级联的解决方法
随机推荐
The Industrial Metaverse Brings Changes to Industry
CIFAR发布《AI伦理的文化:研讨会报告》【附下载】
ECCV 2022 | FPN错位对齐,实现高效半监督目标检测(PseCo)
Go 言 Go 语,一文看懂 Go 语言文件操作
PHP代码审计7—文件上传漏洞
在线生成接口文档
Kubernetes入门到精通- Operator 模式入门
【CCIG 2022】视觉大模型论坛
powershell和cmd对比
Go language Go language, understand Go language file operation in one article
股票开户广发证券,网上开户安全吗?
如何进行自动化测试?【Eolink分享】
服务器
敏捷开发项目管理的一些心得
2019年海淀区青少年程序设计挑战活动小学组复赛试题详细答案
Flask framework implementations registered encryption, a Flask enterprise class learning 】 【
当前最快的实例分割模型:YOLACT 和 YOLACT++
YOLOv7-Pose尝鲜,基于YOLOv7的关键点模型测评
vantui 组件 van-field 路由切换时,字体样式混乱问题
Scala104-Spark.sql的内置日期时间函数