ES6 ----- Learning Series 2 (deconstruct assignment), es6 ----- deconstruct
I. Deconstruct the definition of value assignment
In simple terms, the assignment = has the same structure on both sides of the number to perform one-to-one assignment.
Ii. deconstruct and assignment Classification
Array deconstruct assign value object deconstruct assign value string deconstruct assign value Boolean deconstruct assign value function parameter deconstruct assign value (the first two values can be understood)
3. Separate interpretation of each category
1. array deconstruct assignment (the following code is displayed and necessary annotations are added for ease of understanding)
{Let a, B, rest; [a, B] = [1, 2]; console. log (a, B); // output 1, 2 directly deconstruct 1 and 2 to a and B}
You can also set the default value for the variable. For example, c in the code below is the default value 3. If the deconstruct for example [a, B, c] = [1, 2] is not deconstruct for c, c is undefined.
{ let a,b,c,rest; [a,b,c=3]=[1,2]; console.log(a,b);}
Scenario 1
①. Variable exchange
{ let a=1; let b=2; [a,b]=[b,a]; console.log(a,b);}
② Directly extract the function return values (results must be obtained first and then retrieved through indexes without deconstruct assignment)
{ function f(){ return [1,2] } let a,b; [a,b]=f(); console.log(a,b);}
③ Retrieve only some required values of the returned results
{Function f () {return [1, 3, 4, 5]} let a, B, c; [a, B] = f (); console. log (a, B); // output 1 4}
④ Don't care about the content length of the array
{Function f () {return [1, 3, 4, 5]} let a, B, c; [,... b] = f (); console. log (a, B); // output 1, [2, 3, 4, 5]}
2. Object deconstruct assignment
{ let o={p:42,q:true}; let {p,q}=o; console.log(p,q);}
Default Value of object deconstruct assignment
{Let {a = 10, B = 5 }={ a: 3}; console. log (a, B); // output 3 5}
Deconstruct and assignment of a slightly complex object
{Let metaData = {title: 'abc', test: [{title: 'test', desc: 'description'}]} let {title: esTitle, test: [{title: cnTitle}]} = metaData; console. log (esTitle, cnTitle); // abc test (equivalent to abc and test in metaData respectively for esTitle and cnTitle )}