In ES5, the assignment of various variables and objects can only be one-to-one. es6 has been reformed. The new standard allows us to assign in groups. Variables correspond to the position of values and assign one by one. This is deconstruction assignment.
string String string Deconstruction Assignment: |
let [w,b,i]='wbi';
console.log(w,b,i);
let [w,b]='wbiokr';
console.log(w,b);
let [w,b,i,o]='wb';
console.log(w,b,i,o);
let [(w)]='wbiokr';
[(w)]='wbiokr';
console.log(w);
When string deconstructs an assignment, the key-value pair is always one-to-one correspondence. The extra value is not assigned to the last key, and the extra key is undefined. |
Array array deconstruction assignment |
let [a,b,c]=[1,2,3];
console.log(a,b,c);
let [a,b]=[1,2,3,4];
console.log(a,b);
let [,a,b]=[1,2,3,4];
console.log(a,b);
let [a,b,c]=[1];
console.log(a,b,c);
let [a,b,c]=[1,2,[3]];
console.log(a,b,c);
let [a,[b]]=[1,2];
let [a,[b]]=[1,[2]];
console.log(a,b);
let [a,b]={a:1,b:2}
let [(a)]=[1];
[(a)]=[1];
console.log(a);
Location corresponds, type corresponds! |
object deconstruction assignment: |
let {a}={a:1};
console.log(a);
let {b}={a:1};
console.log(b);
let {a:c}={a:1};
console.log(c);
let a;
let {a}={a:1};
let a;
{a}={a:1};
console.log(a);
let c;
let {a:c}={a:1};
let c;
{a:c}={a:1};
console.log(c);
let {a,b:{c}}={a:1,b:{c:3}};
console.log(a,b,c);
let {(aaaaq)}={aaaaq:1};
let {a:(a)}={a:1};
{a:(a)}={a:1};
console.log(a);
Like array deconstruction assignment, as long as the location is corresponding, whether nested or not, nested several layers, can be successfully assigned, but when deconstruction assignment, we must pay attention to the format. A bracket problem can kill people if they are not careful in the development process. |
function deconstruction assignment: |
(function([a,b,c]){console.log(a,b,c)})([1,2,3]);//1,2,3
[[1,2],[3,4]].reduce(function([a,b]){console.log(a*b)});//2 , 12
Deconstruction assignment can also assign parameters of scoped functions, and the same function parameters can assign default values. |
Default values in Deconstruction assignments: |
let [a=1]=[];
console.log(a);
let {a,b=true}={a:2};
console.log(a,b);
let {a=true}={a:NaN};
console.log(a);
let {a=true}={a:null};
console.log(a);
let {a=true}={a:undefined};
console.log(a);
function fun(x=1,y=2){
console.log(x,y)
};
fun('s');
fun(2,5);
fun();
function fun2({x,y}={x:1,y:2}){
console.log(x,y);
}
fun2();
fun2({x:2});
Default values are absolutely good things, for example, when we call encapsulated ajax functions, page initialization, will automatically call once, at this time you can not pass the value. |
———-
Deconstruction assignment exchange x and y values: |
Once I was asked how to exchange the values of variables x and y without defining a third variable. Finally, it did, but it really killed more than N of my brain cells. |
var x=2,y=5;
x=y-x;
y=y-x;
x=y+x;
let x=2,y=5;
[x,y]=[y,x];
console.log(x,y)