ES6中js的运算符(?.、?:、? ?、? ?=、)

一、空值合并操作符( ?? )

空值合并操作符( ?? )是一个逻辑操作符,当左侧的操作数为 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

对比

看了上面你可能还不太明白,那么请看下面

//   ||运算符

function(obj){
    var a = obj || {}
}
 
等价于
function(obj){
    var a;
    if(obj === 0 || obj === "" || obj === false || obj === null || obj === undefined){
 	a = {}
    } else {
	a = obj;
    }
}
//  ??运算符

function(obj){
    var a = obj ?? {}
}
 
等价于
function(obj){
    var a;
    if( obj === null || obj === undefined){
 	a = {}
     } else {
	a = obj;
    }
}

二、可选链操作符( ?. )

可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。( ?. ) 操作符的功能类似于( . )链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined

当尝试访问可能不存在的对象属性时,可选链操作符将会使表达式更短、更简明。在探索一个对象的内容时,如果不能确定哪些属性必定存在,可选链操作符也是很有帮助的。

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: 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()

三、??= 空赋值运算符

当你觉得这就结束的时候,ES2022 为我们配套带来了 ??= 赋值操作符号,同样它于 ||= 运算符相似,同上赋值条件存在差异。

??= 运算符英文全称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

四、?:三目运算符

匹配pattern但不获取匹配结果

?: 又叫条件运算符,接受三个运算数:条件 ?  条件为真时要执行的表达式 : 条件为假时要执行的表达式。实际效果:

举例1:
function checkCharge(charge) {
    return (charge > 0) ? '可用' : '需充值' 
}
console.log(checkCharge(20)) // => 可用
console.log(checkCharge(0)) // => 需充值


举例2:
var str = 'aaabbb'
var reg = /(a+)(?:b+)/
str.match(reg)

// ["aaabbb", "aaa", index: 0, input: "aaabbb", groups: undefined]

猜你喜欢

转载自blog.csdn.net/ShIcily/article/details/121673976