当前位置:网站首页>ES6 --- four powerful operators (?,? =,?.,?:)
ES6 --- four powerful operators (?,? =,?.,?:)
2022-07-25 20:58:00 【Java Academic Forum】
1. Null merge operator (?? )
- Null merge operator ( ?? ) It's a logical operator , When the operands on the left are null perhaps undefined when , Back to its Right operand , Otherwise return to Left hand operands . Null merge operator ( ?? ) And logic or operators ( || ) Different , The logical or operator returns the right-hand operand when the left-hand operand is false .
Be careful : Only when the operand is null、undefined The predicted data will only be used when these two false values , however JS The false value contains : Undefined undefined、 An empty object null、 The number 0、 Empty numbers NaN、 Boolean false, An empty string '', Be sure to pay attention to .
// A simple example
null ?? 5 // => 5
3 ?? 5 // => 3const nullValue = null;
const emptyText = ""; // An empty string , It's a false value ,Boolean("") === false
const someNumber = 42;
const valA = nullValue ?? "valA The default value of ";
const valB = emptyText ?? "valB The default value of ";
const valC = someNumber ?? 0;
console.log(valA); // "valA The default value of "
console.log(valB); // ""( Although the empty string is a false value , But it's not null perhaps undefined)
console.log(valC); // 422. Null assignment operator (??= )
- ??= Also known as the null assignment operator , Related to the non null operator above . Look at the connection between them :
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) {
// It can also be given as null The default value of
options.gameSpeed ??= 1
options.gameDiff ??= 'easy'
return options
}Only if the value is null or undefined when , This assignment operator will assign . The above example highlights that this operator is essentially Syntax sugar with null assignment
3. Optional chain operator (?. )
- Optional chain operator ( ?. ) Allows you to read the value of an attribute deep in the chain of connected objects , Instead of explicitly verifying that each reference in the chain is valid .( ?. ) The function of the operator is similar to ( . ) Chain operators , The difference is , The reference is empty (nullish ) (null perhaps undefined) It doesn't cause errors , The short-circuit return value of this expression is undefined. When used with function calls , If the given function does not exist , Then return to undefined.
- When trying to access properties of an object that may not exist , The optional chain operator will make the expression shorter 、 More concise . When exploring the content of an object , If you're not sure which attributes must exist , The optional chain operator is also very helpful .
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
// Equate to
a == null ? undefined : a.b
a?.[x]
// Equate to
a == null ? undefined : a[x]
a?.b()
// Equate to
a == null ? undefined : a.b()
a?.()
// Equate to
a == null ? undefined : a()Take a chestnut :
let travelPlans = {
destination: 'DC',
monday: {
location: 'National Mall',
budget: 200,
host: null
}
}
let res = travelPlans?.tuesday?.location ?? "locahost"; // => locahost
let res2 = travelPlans?.host; // => undefinedThis location Where did it come from ? This tuesday Where did it come from ? Even if it's not outside travelPlans There is no location and tuesday ah !!!
let res = travelPlans?.tuesday?.location;
<= Equivalent =>
let res = travelPlans&& travelPlans.tuesday&& travelPlans.tuesday.locationBe careful : The function is to judge the object (travelPlans) Under the (tuesday) Under the (location) Is it null perhaps undefined, When one of the chains is null perhaps undefined When it returns undefined, In this way, even if an attribute is missing in the middle, no error will be reported , The double question mark is followed by the default value .
4. Ternary operator ( ?: )
- ?: : It's also called conditional operator , Take three operands : Conditions ? The expression to execute when the condition is true : The expression to execute when the condition is false . The actual effect :
function checkCharge(charge) {
return (charge > 0) ? ' You can use ' : ' Recharge required '
}
console.log(checkCharge(20)) // => You can use
console.log(checkCharge(0)) // => Recharge required 边栏推荐
- How to use buffer queue to realize high concurrent order business (glory Collection Edition)
- Online random coin tossing positive and negative statistical tool
- Niuke-top101-bm38
- 测试用例和缺陷报告模板
- [leetcode] 28. Implement strstr ()
- 程序的编译和运行
- 有哪些优化mysql索引的方式请举例(sqlserver索引优化)
- Opencv learning Fourier transform experience and line direction Fourier transform code
- Remote—基本原理介绍
- leetcode-6130:设计数字容器系统
猜你喜欢

leetcode-155:最小栈

Leetcode skimming -- guess the size of numbers II 375 medium

Remote—基本原理介绍
![[depth] the new LAAS agreement elephant: the key to revitalizing the development of the defi track](/img/ef/33f93225171e2c3e14b7d090c68196.png)
[depth] the new LAAS agreement elephant: the key to revitalizing the development of the defi track
![[paper reading] unpaired image to image translation using cycle consistent advantageous networks](/img/73/69651dd8ecfdddd1cae13a1d223d51.png)
[paper reading] unpaired image to image translation using cycle consistent advantageous networks

The international summit osdi included Taobao system papers for the first time, and end cloud collaborative intelligence was recommended by the keynote speech of the conference

Airtest解决“自动装包”过程中需要输入密码的问题(同适用于随机弹框处理)
What's special about Huawei's innovative solutions to consolidate the foundation of ERP for small and medium-sized enterprises?
![[leetcode] 28. Implement strstr ()](/img/87/0af2da458e53d31012d6535cc132bb.png)
[leetcode] 28. Implement strstr ()

preprocessor directives
随机推荐
[online tutorial] iptables official tutorial -- learning notes 2
【FiddlerTX插件】使用Fiddler抓包腾讯课堂视频下载(抓不到包解决方案)
[FAQ] access the HMS core push service, and the server sends messages. Cause analysis and solutions of common error codes
Force deduction ----- calculate the money of the force deduction bank
Vulnhub | dc: 5 | [actual combat]
Use Navicat to connect to MySQL database through SSH channel (pro test is feasible)
Detailed explanation of document operation
leetcode-6129:全 0 子数组的数目
Step num problem
7.23
Struct, enum type and union
Leetcode skimming -- guess the size of numbers II 375 medium
An interview question about recover in golang
sqlx库使用
一道golang中关于recover的面试题
牛客-TOP101-BM38
租房二三事
Introduction to MySQL engine and InnoDB logical storage structure
zigbee物联网开发平台(工业物联网)
Add startup software items when the win system starts up