当前位置:网站首页>ES6 new - Operator extension
ES6 new - Operator extension
2022-07-27 09:12:00 【Cabbage 007】
Catalog
1. es6 The extension operator of : ...
1.1 Expand array / character string / object
1.4 Convert an array to a true array
1.5 The remaining parameters of the function
2. es6 The extension operator of : Chain judgment operator ?.
Chain judgment operator ?. Three ways of writing :
3. es6 The extension operator of : null Judgment operator ??
4. es6 The extension operator of : Exponential operators ** / **= / ~~
5. es6 The extension operator of : Logical assignment operators ||= / &&= / ??=
1. es6 The extension operator of : ...
effect :
- Expand array / character string / object
- Copy ( Copy ) Array / object ( Shallow copy )
- Merge array / object
- Convert a pseudo array to a true array
- The remaining parameters of the function
1.1 Expand array / character string / object
// Array
const arr = [ ' The sable cicada ',' Wang Zhaojun '.' Yang Yuhua ' ]
console.log(arr)
// character string
console.log(..."hello")
The essence of a string is an array of characters : ['h','e','l','l','o']
// object
const obj = { m1:" The sable cicada ",m2:{name:" Xi Shi ",age:18} }
console.log(...obj) // Will report a mistake Should be console.log({...obj})

Find the maximum and minimum of an array
const arr = [ 17,6,25,38,13 ]
console.log( Math.max(...arr) )
console.log( Min.max(...arr) )
![]()
1.2 Copy the array / object
// Array
const arr1 = [" The sable cicada "," Wang Zhaojun "," Jade bracelet "]
const arr2 = [ ...arr1 ]
console.log(arr2)
arr2.push(" Xi Shi ")
console.log(arr1)
//arr1 and arr2 Are independent of each other , They don't influence each other

// object
const obj1 = { m1:" The sable cicada ", m2:{ name:" Xi Shi ",age:18} }
const obj2 = { ...obj1 }
console.log(obj2)
obj2.m1 = " Li Qin ";
console.log(obj1)
//obj1 and obj2 Are independent of each other , They don't influence each other

obj2.m2.age = 20
console.log(obj1) // ... For light copy , Only the first level objects can be copied

1.3 Merge array / object
// Array
const arr1 = [' durant '," Owen "]
const arr2 = [" harden "," Griffin "]
const arr = [...arr1,...arr2]
console.log(arr)

// object
const obj1 = { name:" Basketball ",price:199 };
const obj2 = { brand:" Spalding ",address:" Beijing " }
const obj = { ...obj1,...obj2 } // When there are duplicate attributes , The back covers the front
console.log(obj)

1.4 Convert an array to a true array
function add(){
console.log(...arguments)
console.log([...arguments]) }
add(1,2,3,4,5)

1.5 The remaining parameters of the function
function fn(...args){ console.log(args) }
fn(1,2,3,4)

2. es6 The extension operator of : Chain judgment operator ?.
const obj = { name:"KD",age:33 }
// hold obj.name Attribute value to lowercase
console.log(obj.name.toLowerCase()) Output :kd
// hold obj.nickname Attribute value to lowercase
console.log(obj.nickname.toLowerCase()) Report errors
// The correct approach : Read a property inside the object , You often need to judge , Whether the upper object of the property exists
if(obj.nickname){ console.log(obj.nickname.toLowerCase()) }
// Ternary operator ?:
const nickname = obj.nickname ? obj.nickname.toLowerCase() : undefined
console.log(nickname)
// Use ?. Simplify the writing above
console.log( obj.nickname?. toLowerCase()) // Chain judgment operator , Judge directly in the chain call
Output :undefined
// If the object on the left is null perhaps undefined, It's not going to go down , return undefined It stopped.
Chain judgment operator ?. Three ways of writing :
1.obj?.prop Does the object property exist
2.obj?[ expr ] Does the object property exist
3.obj.func?.(...args) Whether the object method exists
matters needing attention :
Short circuit mechanism : ?. The chain judgment operator is equivalent to a short circuit mechanism , As long as the conditions are not met , No more execution
3. es6 The extension operator of : null Judgment operator ??
When reading object properties , If the value of a property is null or undefined,
Sometimes you need to specify default values for them , The common way is through || Operator to specify the default value
function add(options){
let x = options.x || 12
let y = options.y || 30
return x+y }
The above code is through || Operator to specify the default value , But this is wrong , The developer's original intention is , As long as the value of the attribute is null or undefined, The default value will take effect , But if the value of the attribute is An empty string or false or 0 , The default value will also take effect .
console.log({ x:33,y:66 }) Output :99
console.log({ }) Output :42
console.log({ x:0,y:0 }) Output :42
console.log({ x:"",y:"??" }) Output :12??
To avoid that ,es6 Introduced a new null Judgment operator ??, He behaves like ||, But only the value to the left of the operator is null or undefined when , To return the value on the right .
function add(options){
let x = options.x?? 12
let y = options.y?? 30
return x+y }
console.log({ x:33,y:66 }) Output :99
console.log({ }) Output :42
console.log({ x:0,y:0 }) Output :0
console.log({ x:"",y:"??" }) Output :0
In the above code , The default value is only on the left. The attribute value is null or undefined when , Will take effect .
The purpose of this operator ,1. Chain following judgment operator ?. In combination with ,2. by null or undefined Set the default value
function add(options){
let x = options?.x?? 12
let y = options?.y?? 30
return x+y }
console.log({ x:1,y:8 }) Output :99
console.log({ }) Output :42
console.log({ x:0,y:0 }) Output :0
console.log({ x:"hello",y:"2020" }) Output :hello2020
console.log(add()) Output :42
matters needing attention :
priority : ! > && > || There is no need to add parentheses when they appear at the same time
?? In essence, it is a logical operation , It works with two other logical operators && and || There is a priority issue .
Different priorities , It often leads to different results of logical operations , Now the rule is , If multiple logical operators are used together , Priority must be indicated in parentheses , Otherwise, an error will be reported .
const x = null
const y = 12
If you don't add brackets, you will report an error
console.log(x || y ?? x)
console.log(x ?? y && x)
You need to add parentheses
console.log((x || y) ?? x) Output :12
console.log((x ?? y) && x) Output :null
4. es6 The extension operator of : Exponential operators ** / **= / ~~
Exponential operators : ** ( No spaces in between )
Exponential assignment operator : **= ( Write it together , You can't have Spaces )
~: According to the not
~~: Bitwise negation and then negation , Change decimals into integers
stay js Floating point numbers can be changed into integers , Than parsrInt fast
1. Exponential operators
Calculation 2 The third power of
es5
console.log(2 * 2 * 2)
console.log(Math.pow(2,3))
es6
console.log(2 ** 3)
2. Exponential assignment
3 The result of the fourth power of is re assigned to itself
let x = 3
es5
x = x * x * x * x
x = Math.pow(3,4)
es6
x **= 4
x = x ** 4
3. two ~~ Reverse and round
console.log(~~3.14) Output :3
console.log(~~-3.14) Output :-3
console.log(~~0) Output :0
5. es6 The extension operator of : Logical assignment operators ||= / &&= / ??=
Logical assignment operators , Combine logical operators with assignment operators
||= : Or assignment operator
&&= : And the assignment operator
??= : null Assignment operator
purpose : Set default values for variables or properties
Or assignment operator
x ||= y Equate to x || (x=y)
And the assignment operator
x &&= y Equate to x && (x=y)
null Assignment operator
x ??= y Equate to x ?? (x=y)
Set default values for variables :
user.id = uesr.id || 1 Equate to => user.id ||= 1
function ajax (options){
options.method = options.method ?? "get"
options.dataType ??( options.method = "json" ) }
Equate to :
function ajax (options){
options.method ??= "get"
options.dataType ??= "json" }
边栏推荐
- Save Xiaoyi from Netease written test -- a typical application of Manhattan distance
- pollFirst(),pollLast(),peekFirst(),peekLast()
- DNS域名空间
- linux安装和远程连接mysql记录
- npm install报错 强制安装
- B tree
- BOM的常用操作和有关获取页面/窗口高度、宽度及滚动的兼容性写法
- Interface test tool - JMeter pressure test use
- async/await的执行顺序以及宏任务和微任务
- Can "Gulangyu yuancosmos" become an "upgraded sample" of China's cultural tourism industry
猜你喜欢

Music experience ceiling! Emotional design details of 14 Netease cloud music

How to optimize the deep learning model to improve the reasoning speed
![[acl2020] a novel method of component syntax tree serialization](/img/24/b8ec489966f7b1deef82b2eefa4d1b.png)
[acl2020] a novel method of component syntax tree serialization

Deep understanding of Kalman filter (3): multidimensional Kalman filter

Rewrite the tensorrt version deployment code of yolox

Is the operation of assigning values to int variables atomic?

Some practical, commonly used and increasingly efficient kubernetes aliases

PVT的spatial reduction attention(SRA)

苹果降价600元,对本就溃败的国产旗舰手机几乎是毁灭性打击

CUDA programming-04: CUDA memory model
随机推荐
2036: [Blue Bridge Cup 2022 preliminary] statistical submatrix (two-dimensional prefix sum, one-dimensional prefix sum)
TensorFlow损失函数
Qt中发送信号时参数为结构体或者自定义的类怎么办?
Antdesign a-modal user-defined instruction realizes dragging and zooming in and out
Deep understanding of Kalman filter (2): one dimensional Kalman filter
HUAWEI 机试题:字符串变换最小字符串 js
【进程间通信IPC】- 信号量的学习
Is the operation of assigning values to int variables atomic?
音乐体验天花板!14个网易云音乐的情感化设计细节
DNS域名空间
Matlab uses m file to produce fuzzy controller
SQL exercise set
Hangzhou E-Commerce Research Institute released an explanation of the new term "digital existence"
8 kinds of visual transformer finishing (Part 2)
易语言编程: 让读屏软件可获取标签控件的文本
Save Xiaoyi from Netease written test -- a typical application of Manhattan distance
Huawei machine test question: Martian computing JS
[cloud native kubernetes practice] deploy the rainbow platform under the kubernetes cluster
博客怎么上传动态gif图
Deep understanding of Kalman filter (3): multidimensional Kalman filter