当前位置:网站首页>JS中? ?和??=和?.和 ||的区别
JS中? ?和??=和?.和 ||的区别
2022-07-30 23:09:00 【asdfsdgfsdgfa】
undefined和null是两个比较特殊的数据类型,是不能用点操作符去访问属性的,否则将会报错
let a;
console.log(a?.name); //undefined
console.log(a.name); //报错
let obj = {};
console.log(obj.name); //undefined
console.log(obj?.name?.a); //undefined
console.log(obj.name.a); //报错
?? 与 || 的区别
相同点:
?? 和 || 的用法相同,都是前后是值,中间用符号连接,根据前面的值来判断最终是返回前面的值还是后面的值。
A ?? B
A || B
不同点:
判断的方法不同:
使用 ?? 时,只有A为 null 或者 undefined 时才会返回 B;
使用 || 时,A会先转化为布尔值判断,为true时返回A , false 返回B
// ??
console.log(undefined ?? 2); // 2
console.log(null ?? 2); // 2
console.log(0 ?? 2); // 0
console.log("" ?? 2); // ''
console.log(true ?? 2); // true
console.log(false ?? 2); // false
// ||
console.log(undefined || 2); // 2
console.log(null || 2); // 2
console.log(0 || 2); // 2
console.log("" || 2); // 2
console.log(true || 2); // true
console.log(false || 2); // 2
空值合并操作符 ??
只有当左侧为null
或者undefined
时,才会返回右侧的值
可选链操作符 ?.
?.
允许读取连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。
?.
操作符的功能类似于. 链操作符,不同之处在于,在引用为空,即 null
或者 undefined
的情况下不会引起错误,该表达式短路返回值。
const obj = { a: { b: [{ name: "obj" }] } };
// 原本的写法
console.log(obj && obj.a && obj.a.b.length && obj.a.b[0].name); //obj
// 可选链写法
console.log(obj?.a?.b?.[0]?.name); // obj
console.log(obj?.b?.c?.d); // undefined
?.可以和 ?? 运算符结合使用
const obj = { a: { name: "obj" } };
console.log(obj?.a?.b ?? "hello world"); // hello world
空值赋值运算符(??=)
当??=左侧的值为null、undefined的时候,才会将右侧变量的值赋值给左侧变量.其他所有值都不会进行赋值
let a = "你好";
let b = null;
let c = undefined;
let d = 0;
let e = "";
let f = true;
let g = false;
console.log((b ??= a)); // 你好
console.log((c ??= a)); // 你好
console.log((d ??= a)); // 0
console.log((e ??= a)); // ''
console.log((f ??= a)); // true
console.log((g ??= a)); // false
console.log(b); // 你好
console.log(c); // 你好
console.log(d); // 0
console.log(e); // ''
console.log(f); // true
console.log(g); // false
边栏推荐
- Achievements of Science and Technology (31)
- StoneDB 为何敢称业界唯一开源的 MySQL 原生 HTAP 数据库?
- Debezium报错系列之二十:task failed to create new topic.Ensure that the task is authorized to create topics
- HF2022-EzPHP复现
- Day016 Classes and Objects
- 2sk2225 Substitute 3A/1500V Chinese Documentation【PDF Data Book】
- 抽象类和接口(学习笔记)
- 打动中产精英群体,全新红旗H5用产品力跑赢需求
- MySQL索引常见面试题(2022版)
- 2021GDCPC广东省大学生程序设计竞赛 H.History
猜你喜欢
随机推荐
电脑快捷方式图标变白解决方案
"Code execution cannot continue because MSVCP140.dll was not found, reinstalling the program may resolve the problem, etc." Solutions
“蔚来杯“2022牛客暑期多校训练营4 DHKLN
$\text{ARC 145}$
MySQL索引常见面试题(2022版)
QT 在父类中添加子类的流程,object tree,
“由于找不到MSVCP140.dll,无法继续执行代码,重新安装程序可能会解决此问题等”解决方案
StoneDB 为何敢称业界唯一开源的 MySQL 原生 HTAP 数据库?
Go语学习笔记 - gorm使用 - gorm处理错误 Web框架Gin(十)
反转链表-就地逆置法
Go的Gin框架学习
Apache Doris series: detailed steps for installation and deployment
连号区间数
Alibaba Cloud video on demand + project combat
通过社交媒体建立个人IP的 5 种行之有效的策略
BFS题单总结
打动中产精英群体,全新红旗H5用产品力跑赢需求
2022.7.28
CPM:A large-scale generative chinese pre-trained lanuage model
网安学习-内网渗透3