Deconstruction assignment
1.1. Array deconstruction assignment
// Assign to a variable through an array
let arr = [1.2.3]
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
let [a,b,c] = [1.2.3]
console.log(a);
console.log(b);
console.log(c);
Copy the code
1.1.1. Pattern matching
If the pattern is the same on both sides of the equal sign, the variable on the left will be assigned the corresponding value
let [a,[[b],c]] = [1The [[2].3]]
console.log(a);
console.log(b);
console.log(c);
Copy the code
1.1.2. Incomplete deconstruction
// Not completely deconstructed
let [x,y,u] = [1.2.3.4]
console.log(x);
console.log(y);
console.log(u);
Copy the code
1.1.3. Nested pattern
let [a,[[b],c]] = [1The [[2].3]]
console.log(a);
console.log(b);
console.log(c);
Copy the code
1.1.4. The default value
// Specify a default value
let [f = true] = []
console.log(f);
let [a,b="y"] = ['a']
console.log(b);
// Note that es6 internal use === check whether undefined if undefined the default value takes effect
let [x = 1] = [null]
let [y = 2] = [undefined]
console.log(x); // null
console.log(y); / / 2
Copy the code
1.1.4.1. Lazy evaluation
// lazy evaluation
function f(){
return 'fff'
}
// let [x = f()] = [1]
let [x = f()] = []
console.log(x);
Copy the code
1.1.4.2. Default values can refer to other variables that are destructively assigned
// Default values can refer to other variables that are destructively assigned as long as the variables are already declared
// let [x= 1,y=x] = []
// console.log(x); / / 1
// console.log(y);
// let [x = y,y=1] = [] // from left to right
// let [y = 1 , x = y] = []
// console.log(x);
// console.log(y);
Copy the code
2. Object deconstruction assignment
2.1. Define usage notes
let person = {
name:"chris".age:33
}
// let {name,age} = person;
// Note that object deconstruction is not the same as array and has nothing to do with order
let {age:age,name:name} = person;
console.log(name);
console.log(age);
let {sex} = person;
console.log(sex); // Unsuccessfully destruct returns undefined
// What is really assigned is the nature of the latter object's deconstruction assignment
// The attribute of the same name is first found and assigned to the variable of the latter
let {name:name1} = person
console.log(name1);
Copy the code
2.2. Inherited properties can be fetched
const obj1 = {};
const obj2 = {name:'laney'}
Object.setPrototypeOf(obj1,obj2)
// obj1.__proto__ = obj2
const {name} = obj1;
console.log(name);
Copy the code
2.3. Specify default values
// The value of the object attribute is strictly === undefined
const {x = 1} = {x:undefined}
const {y = 3} = {y:null}
console.log(x);
console.log(y);
Copy the code