当前位置:网站首页>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" }
边栏推荐
- Primary function t1744963 character writing
- Software testing function testing a full set of common interview questions [function testing - zero foundation] essential 4-1
- Encountered 7 file(s) that should have been pointers, but weren‘t
- 500报错
- How to register code cloud account
- CUDA programming-01: build CUDA Programming Environment
- openharmony萌新贡献指南
- 【每日算法Day 94】经典面试题:机器人的运动范围
- Storage and computing engine
- 拍卖行做VC,第一次出手就投了个Web3
猜你喜欢

Mangodb简单使用

Pyqt5 rapid development and practice 4.1 qmainwindow

Flex layout (actual Xiaomi official website)

linux安装和远程连接mysql记录

CUDA programming-02: first knowledge of CUDA Programming

Rewrite the tensorrt version deployment code of yolox

async/await的执行顺序以及宏任务和微任务

被三星和台积电挤压的Intel终放下身段,为中国芯片定制芯片工艺

PVT的spatial reduction attention(SRA)

The execution sequence of async/await, macro tasks and micro tasks
随机推荐
Install Oracle under Linux, connect local pl/sql to Oracle import table under Linux, and create new user and password
ArkUI中的显式动画
How to deploy yolov6 with tensorrt
Qt中发送信号时参数为结构体或者自定义的类怎么办?
[daily algorithm day 96] Tencent interview question: merge two ordered arrays
Explicit animation in arkui
Restful
HUAWEI 机试题:火星文计算 js
Rewrite the tensorrt version deployment code of yolox
JS call and apply
Tensorflow loss function
npm install报错 强制安装
Qdoublevalidator does not take effect solution
DNS域名空间
Interface test tool - JMeter pressure test use
Encountered 7 file(s) that should have been pointers, but weren‘t
Easy language programming: allow the screen reading software to obtain the text of the label control
1.3.1 Full Permutation Problem
CUDA programming-02: first knowledge of CUDA Programming
【微服务~Sentinel】Sentinel之dashboard控制面板