ES6中的运算符(?.、? ?、? ?=、)
不进步就是落后,不学习就会退步,时间在移动,社会在发展,行动起来吧我的老宝贝们。一起加油。
空值合并操作符??
定义 :空值合并操作符(??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。
与逻辑或操作符(||)不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。
例子
为空判断时写法
- 普通型
if(value !== null && value !== undefined && value !== ''){
//...
}
- 用空值合并运算符
if(value??'' !== ''){
//...
}
const res={data:{price:0}}
const price=res.data?.price??'123'
console.log(price) //0
可选链操作符?.
定义:允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined。
let a;
const b = a.c; //报错
//之前的解决办法,返回undefined
const d = a && a.c;
//使用可选操作符,返回undefined
const f = a?.c
a?.b 等于 a==null?undefined : a.b
空赋值运算符 ??=
定义:
运算符英文全称Logical nullish assignment,中文翻译为逻辑空赋值。
逻辑空赋值运算符 (x ??= y) 仅在 x 是 null 或 undefined 时对其赋值。
let a = 0;
a ??= 1;
console.log(a); // 0
let b = null;
b ??= 1;
console.log(b); // 1