Deconstruction assignment syntax is a JS expression. ES6 allowed according to a certain pattern, and the object is extracted from an array of values, assignment variable, which is called deconstruction. By destructuring assignment, that the attribute / value taken from the subject / array, assigned to other variables.
ES6 appear before the deconstruction of the assignment, we need to assign values to variables can only be directly specified value.
such as:
let a = 1;
let b = 2;
let c = 3;
let d = 4;
let e = 5;
But now, ES6 allow written as such.
In essence, such an approach are " 模式匹配
,", i.e., as long as the same pattern on both sides of the equal sign, will be variable on the left corresponding to the given value.
let [a, b, c, d, e] = [1, 2, 3, 4, 5];
ES6 deconstruction not only for the array, the object can also be used , as follows:
let { name, age } = { name: "张三", age: 18 };
console.log(name);
console.log(age);
Results:
Note: The
elements of the array are arranged in order, the value of the variable is determined by its location; no order and properties of the object, attribute variables must be the same name, in order to get the correct value:
let { name, age } = { name: "张三", age: 18 };
console.log(name); //张三
console.log(age); // 18
// ===========================================
let { age } = { name: "张三", age: 18 };
console.log(age); // 18
To exchange variables: a deconstruction expression in two variables can be exchanged, it is no longer necessary to exchange the third variable.
var a = 1;
var b = 2;
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1
You can be given a default value give variable. When the object is not to extract the attributes corresponding to the variable to be given default values.
var {a = 2, b = 3} = {a: 1};
console.log(a); // 1
// 此时要提取的对象没有对应的属性,便打印默认值
console.log(b); // 3