1. The definition of destructuring assignment
A simple understanding is that the left and right sides of the assignment = sign have the same structure to perform one-to-one assignment statements
2. Classification of destructuring assignment
Array destructuring assignment Object destructuring assignment String destructuring assignment Boolean value destructuring assignment Function parameter destructuring assignment Numerical destructuring assignment ( Just focus on understanding the first two)
3. Explain each category separately
1. Array Destructuring assignment (the code is shown below, and necessary comments are added for easy understanding)
{ let a,b,rest; [a,b]=[1,2]; console.log(a,b);//输出1,2 直接将1和2解构到a和b}
You can also set default values for variables. For example, c in the following code defaults to 3 If deconstruction, for example [a,b,c]=[1,2], c is not deconstructed, then c is undefined
{ let a,b,c,rest; [a,b,c=3]=[1,2]; console.log(a,b);}
Usage scenario 1
①、Variable exchange
{ let a=1; let b=2; [a,b]=[b,a]; console.log(a,b); }
①
## Get the result and then retrieve it through the index)
{ function f(){return [1,2] } let a,b; [a,b]=f(); console.log(a,b); }
③. Only take out some required values of the returned result
{ function f(){return [1,2,3,4,5] } let a,b,c; [a,,,b]=f(); console.log(a,b); // 输出1 4 }
④.No Care about the content length of the array
{ function f(){return [1,2,3,4,5] } let a,b,c; [a,...b]=f(); console.log(a,b);//输出1,[2,3,4,5] }
{ let o={p:42,q:true}; let {p,q}=o; console.log(p,q); }
{ let {a=10,b=5}={a:3}; console.log(a,b);//输出3 5 }
###
{ let metaData={ title:'abc', test:[{ title:'test', desc:'description'}] } let {title:esTitle,test:[{title:cnTitle}]}=metaData; console.log(esTitle,cnTitle);//abc test (相当于esTitle和cnTitle分别对应metaData里面的abc和test) }
The above is the detailed content of Detailed explanation of destructuring assignment examples for ES6 learning. For more information, please follow other related articles on the PHP Chinese website!