1, ES6 allowed according to a certain pattern, extract the value from the array and the object, the assignment of the variable, which is called deconstruction (Distructuring);
let [a, b, c] = [3,5,6]; // corresponds to a = 3, b = 5, c = 6
In essence, such an approach in "pattern matching", as long as the same pattern on both sides of the equal sign, the variable on the left will be given corresponding values. If unsuccessful deconstruct the value of the variable is equal to undefined
Another situation is not fully capable of deconstruction, that models the left of the equal sign, only an array of matching the right part of the equal sign. In this case, deconstruction can still succeed.
2, deconstruction array assignment
Complete deconstruction:
let [a,b,c] = [6,7,8]; // a=6,b=7,c=8
Incomplete deconstruction
let [a,[b],c] = [2,[4,6],7]; // a=2,b=4,c=7
Collection of deconstruction:
let [head,...tail] = [1,3,4,5,6]; // head= 1,tail=[3,4,5,6]
Set the default value (default value may also be a function):
let [x,y='b']=['a']; //x=a,y=b
3, the object deconstruction assignment
① deconstruction variable name in the object properties must exist in order to take values;
let {name, age} = {name: 'zjl', age: 18} // name = 'zjl', age = 18 Note: variable name must be left in the object property name
② If the variable name with the name attribute is inconsistent, must be written as follows, renaming
let {name:username,age}={name:'zjl',age:18} // username='zjl',age=18
③ According to a second known point, destructuring assignment is abbreviated in the following way
let {name: name, age: age} = {name: 'zjl', age: 18} // equal when the object attributes and attribute values can be abbreviated
④ nested deconstruction
let {p:[x,{y}]}={p:['hello',{y:'world'}]} // x=hello,y=world
⑤ objects deconstruction can also set a default
let {x:y=9}={10} //y=9
4, deconstruction string assignment
① When deconstruction, the string is converted into a similar array of objects.
const [a,b,c]='zjl' // a='z',b='j',c='l'
② The length attribute string of deconstruction
let {length}='hello' //length=5
5, and an array of Boolean values deconstruction assignment
When deconstruction, if the right side of the equal sign is a numerical and Boolean values, it will first turn objects
let {toString: s} = 123; //函数 s === Number.prototype.toString true
let {toString: s} = true; //函数 s === Boolean.prototype.toString true
6, uses deconstruction assignment
① exchange value of the variable
let x = 1; let y = 2; [x, y] = [y, x];
② function return value
function example() { return [1, 2, 3]; }
let [a, b, c] = example();
③ defined function parameters
function f([x, y, z]) { ... }
f([1, 2, 3]);
④ specified value introduced on demand import module