Object destruct assignment
- Basic usage
let obj = {
name:'Joe',
age:23,
like:'LOL'
}
let{name,age,like} = obj console.log(name,age,likeCopy the code
let obj = {
name:'Joe',
age:23,
like:'LOL'
}
let{age,name,like} = obj console.log(name,age,likeCopy the code
let obj = {
name:'Joe',
age:23,
like:'LOL'
}
let{age} = obj console.log(age) // Output: 23Copy the code
let obj = {
name:'Joe',
age:23,
like:'LOL'
}
let obj2 = {
name:'bill',
age:18,
like:"QQ speed"
}
let{age,name,like} = obj console.log(name,age,likelet{the age: age1, name: name1, like: like1} = obj2. The console log (age1, name1, like1) / / output: 18"Bill" "QQ speed"
Copy the code
Tip
- On the left
{}
Contains property names in order independent of the object properties to be deconstructed on the right - On the left
{}
The number in does not need to be the same as the number of objects to be deconstructed on the right - general
{}
Is the same as the property name of the object to be deconstructed on the right, but if multiple objects need to be received with the new property name
Destruct with default values
let obj = {
name:'Joe',
age:23,
like:'LOL'
}
let {age,like='Knock code'} = obj console.log(age,like"LOL"
Copy the code
let obj = {
name:'Joe',
age:23,
like:'LOL'
}
let {age,skill='5 lines of code a second'} = obj console.log(age,skill) // Output: 23"Five lines of code a second."
Copy the code
In combination with… Extend operator deconstruction
let obj = {
name:'Joe',
age:23,
like:'LOL'
}
let{age,... Rest} = obj console.log(age,rest)"Zhang", like: "LOL"}
Copy the code
Complex object deconstruction
let tree= {
size:{
width:100,
height:200,
},
child:['span'.'a'],
element:'div'
}
let{size:{width}, child:[child1], Element} = tree console.log(width,child1"span" "div"
Copy the code
Complex object deconstruction tip: Keep the left object structure consistent with the right object structure
Business use
Function argument destruct assignment
functionAdd ({x, y} {). The console log (x + y)} the add ({2} x: 1, y:) / / output: 3Copy the code
functionAdd ({x = 3, y}) {the console. The log (x + y)} the add ({2} y:) / / output: 5Copy the code
functionAdd ({x = 3, y} = {} {the console. The log (x, y)} the add () / / output: 3 undefinedCopy the code
Array destruct assignment
To be continued…