当前位置:网站首页>ES6---4个强大运算符(??、??=、?.、?:)
ES6---4个强大运算符(??、??=、?.、?:)
2022-07-25 20:53:00 【Java学术趴】
1. 空值合并操作符(?? )
- 空值合并操作符( ?? )是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。 空值合并操作符( ?? )与逻辑或操作符( || )不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。
注意:只有当操作数为 null、undefined 这两个假值的时候才会使用预测的数据,但是 JS 中假值包含:未定义 undefined、空对象 null、数值 0、空数字 NaN、布尔false,空字符串'',一定要注意。
// 简单例子
null ?? 5 // => 5
3 ?? 5 // => 3const 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); // 422. 空赋值运算符(??= )
- ??= 也被称为空赋值运算符,与上面的非空运算符相关。看看它们之间的联系:
var x = null
var y = 5
console.log(x ??= y) // => 5
console.log(x = (x ?? y)) // => 5
let a = 0;
a ??= 1;
console.log(a); // 0
let b = null;
b ??= 1;
console.log(b); // 1
function gameSettingsWithNullish(options) {
// 还可以多级别调用之后给定其为null的默认值
options.gameSpeed ??= 1
options.gameDiff ??= 'easy'
return options
}仅当值为 null 或 undefined 时,此赋值运算符才会赋值。上面的例子强调了这个运算符本质上是空赋值的语法糖
3. 可选链操作符(?. )
- 可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。( ?. ) 操作符的功能类似于( . )链式操作符,不同之处在于,在引用为空(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: undefineda?.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()举个栗子:
let travelPlans = {
destination: 'DC',
monday: {
location: 'National Mall',
budget: 200,
host: null
}
}
let res = travelPlans?.tuesday?.location ?? "locahost"; // => locahost
let res2 = travelPlans?.host; // => undefined这个location是哪里来的呢?这个tuesday又是哪里来的呢?就算不是外面的travelPlans这个对象里也没有location和tuesday啊!!!
let res = travelPlans?.tuesday?.location;
<=等价=>
let res = travelPlans&& travelPlans.tuesday&& travelPlans.tuesday.location注意: 作用就是判断这个对象(travelPlans)下的(tuesday)下的(location)是否为null或者undefined,当其中一链为null或者undefined时就返回undefined,这样即使中间缺少一个属性也不会报错,双问号后面接的就是默认值。
4. 三元运算符( ?: )
- ?: :又叫条件运算符,接受三个运算数:条件 ? 条件为真时要执行的表达式 : 条件为假时要执行的表达式。实际效果:
function checkCharge(charge) {
return (charge > 0) ? '可用' : '需充值'
}
console.log(checkCharge(20)) // => 可用
console.log(checkCharge(0)) // => 需充值边栏推荐
- [fiddlertx plug-in] use Fiddler to capture the package Tencent classroom video download (unable to capture the package solution)
- Product principles of non-financial decentralized application
- Question and answer 47: geeks have an appointment - the current monitoring system construction of CSC
- Open source SPL enhances mangodb computing
- ROS_ Rqt toolbox
- How to choose a microservice registration center?
- Add startup software items when the win system starts up
- Explain the principle of MySQL master-slave replication in detail
- Compilation and operation of program
- leetcode-6131:不可能得到的最短骰子序列
猜你喜欢

Online XML to JSON tool

Leetcode skimming -- guess the size of numbers II 375 medium
![[cloud native] use of Nacos taskmanager task management](/img/af/f1c5359e7dbcf51f02fa32839539b2.png)
[cloud native] use of Nacos taskmanager task management

【FiddlerTX插件】使用Fiddler抓包腾讯课堂视频下载(抓不到包解决方案)

IEC61131 address representation

结构体,枚举类型与联合体

How to use buffer queue to realize high concurrent order business (glory Collection Edition)

Leetcode-919: complete binary tree inserter

Force deduction ----- calculate the money of the force deduction bank

How to realize reliable transmission with UDP?
随机推荐
Leetcode-6126: designing a food scoring system
Unity vs -- the default debugging in VS is to start rather than attach to unity debugging
Leetcode customs clearance: hash table six, this is really a little simple
Sum of two numbers and three numbers
【FiddlerTX插件】使用Fiddler抓包腾讯课堂视频下载(抓不到包解决方案)
一道golang中关于recover的面试题
两数,三数之和
测试用例和缺陷报告模板
Force deduction ----- calculate the money of the force deduction bank
Use of C log4net: add file name and line number to the output log content; Repackaged class output file name and line number
Question and answer 47: geeks have an appointment - the current monitoring system construction of CSC
Online random coin tossing positive and negative statistical tool
Leetcode-6129: number of all 0 subarrays
MPI学习笔记(二):矩阵相乘的两种实现方法
Rent two or three things
Achieve accurate positioning based on Tencent map, and realize the attendance punch function of wechat applet
Leetcode-155: minimum stack
C language file reading and writing
Rand1 generates rand9
103. (cesium chapter) cesium honeycomb diagram (square)