ES6 allows you to extract values from arrays, assign values to variables, and deconstruct objects
1. Array deconstruction
let [a, b, c] = [1.2.3];
console.log(a)/ / 1
console.log(b)/ / 2
console.log(c)/ / 3
// If the deconstruction fails, the value of the variable is undefined
Copy the code
2. Object deconstruction
let person = { name: 'zhangsan'.age: 20 };
let { name, age } = person;
console.log(name); // 'zhangsan'
console.log(age); / / 20
let {name: myName, age: myAge} = person; // myName myAge belongs to an alias
console.log(myName); // 'zhangsan'
console.log(myAge); / / 20
Copy the code
3. Summary
- Deconstructing assignment involves breaking up data structures and assigning values to variables
- If the structure is unsuccessful and the variable does not match the number of values, the variable value is undefined
- Array destructions are wrapped in brackets and multiple variables are separated by commas, and object destructions are wrapped in curly braces and multiple variables are separated by commas
- Using deconstructed assignment makes it easy to fetch properties and methods from objects