空值合并操作符( ?? )
空值合并操作符( ?? )当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。逻辑或操作符会在左侧操作数为假值时返回右侧操作数。
如果左边的值为null或undefined 返回其右侧操作数(如果左边的值为假值fasle 还是会返回左侧操作数)
如果左边 不是 null或undefined 就返回左侧操作数
const nullValue = null;
const emptyText = ""; // 空字符串,是一个假值,Boolean("") === false
const someNumber = 42;
const valA = nullValue ?? "valA 的默认值";
const valB = emptyText ?? "valB 的默认值";
const valC = someNumber ?? 0;
console.log(valA); // "valA 的默认值"
console.log(valB); // ""(空字符串虽然是假值,但不是 null 或者 undefined)
console.log(valC); // 42
可选链操作符( ?. )
如果给定的函数或者值不存在,则返回 undefined
a?.b
// 等同于
a == null ? undefined : a.b
a?.[x]
// 等同于
a == null ? undefined : a[x]
a?.b()
// 等同于
a == null ? undefined : a.b()
a?.()
// 等同于
a == null ? undefined : a()
如果不等于null 就会正常返回
如果等于null 就会返回undefined
??= 空赋值运算符
个人认为 这个运算符是奇葩运算符 用不到
逻辑空赋值运算符 (x ??= y) 仅在 x 是 null 或 undefined 时对其赋值
let a = 0;
a ??= 1;
console.log(a); // 0 当前不等于null 或 undefined
let b = null;
b ??= 1;
console.log(b); // 1 如果等于null 或undefined就会赋值
?:三元运算符
?: 又叫条件运算符,接受三个运算数:条件 ? 条件为真时要执行的表达式 : 条件为假时要执行的表达式。实际效果:
let func;
func = this.type === 'one' ? one : two
判断条件 如果当前条件满足 返回?后面的 one
如果为假false 返回:后面的 two