0x000 overview
To be honest, deconstruction assignment is very popular, especially when it is used with other es6, so how to simply say that deconstruction assignment, for example: Deconstruction assignment is a coin splitting machine. Put all dimes into the coin splitting machine, he will automatically divide all the coins and take out what you want!
0x001 deconstruct array
You can retrieve a data or a set of data from an array
-
ordinary
let [a, b, c]=[1,2,3] console.log(a) // 1 console.log(b) // 2 console.log(c) // 3
-
Use with remaining parameters
let [a, b, ...c]=[1,2,3,4,5] console.log(a) // 1 console.log(b) // 2 console.log(c) // [3,4,5]
-
Omit some parameters
let [a, , ...c]=[1,2,3,4,5] console.log(a) // 1 console.log(c) // [3,4,5]
-
Insufficient parameters
let [a, b, c]=[1,2] console.log(a) // 1 console.log(b) // 2 console.log(c) // undefined
-
There are not enough parameters and you don't want to undefined. You can use the default parameters
let [a, b, c=3]=[1,2] console.log(a) // 1 console.log(b) // 2 console.log(c) // 3
-
Deconstruction and assignment of existing variables
let a, b [a, b]=[1,2] console.log(a, b)// 1,2
0x002 interesting array deconstruction chestnut
-
Swap two variables
let a=1,b=2 [a, b]=[b, a] console.log(a) // 2 console.log(b) // 1
-
Get the result of a regular match
let [,match]="hello world".match(/h(e)/) // The matching result is ["he", "e", index: 0, input: "Hello world", groups: defined] console.log(match) // 'e'
0x003 deconstruct object
You can take a property value or a sub object from an object
-
ordinary
let {a, b}={a:1,b:2} console.log(a) // 1 console.log(b) // 2
-
Residual attribute
let {a,...b}={a:1,b:2,c:3} console.log(a) // 1 console.log(b) // {b:2,c:3}
-
Attribute is not enough
let {a, b, c}={a:1,b:2} console.log(a) // 1 console.log(b) // 2 console.log(c) // undefined
-
Insufficient properties to use default parameters
let {a, b, c=3}={a:1,b:2} console.log(a) // 1 console.log(b) // 2 console.log(c) // 3
-
Assign values to new variables
let {a:aa, b:bb}={a:1,b:2} console.log(aa) // 1 console.log(bb) // 2
-
Assign values to new variables and provide default values
let {a:aa, b:bb, c:cc=3}={a:1,b:2} console.log(aa) // 1 console.log(bb) // 2 console.log(cc) // 3
-
Deep objects can also be deconstructed
let {name, books:[book]}={name:"haha",books:['book1']} console.log(name) // 'haha' console.log(book) // 'book1'
-
Deconstruction in iteration
for(let {name} of [{name:1},{name:2}]){ console.log(name) // 1 2 }
-
Deconstruct function parameters
let register({name, pwd}){ console.log(name, pwd) } register({name:'1',pwd:'2'}) //1,2
-
It is special to assign values to existing variables
let a,b ({a, b}={a:1,b:2}) // Priority needs to be raised, otherwise {a, b} will be parsed into code blocks console.log(a, b)// 1, 2