ES6 destructuring assignment of array destructuring assignment

Destructuring assignment

<1> Destructuring assignment is a JavaScript expression that allows you to extract values ​​from an array, or properties from an object , into different variables. ----MDN
<2> The following is the explanation from the novice tutorial

  1. Destructuring assignment is an extension of the assignment operator.
  2. It is a pattern matching for an array or object, and then assigns values ​​to the variables in it.
  3. The code writing is concise and easy to read, and the semantics are clearer; it also facilitates the acquisition of data fields in complex objects.
The following is a collection of content related to the destructuring and assignment of arrays.
1. Simple destructuring assignment

Syntax const[ ] = [ ];
The array on the left of the equal sign is the variable to be assigned, and the array on the right is the array to be destructured. Let’s enter the code below.
const arr = [1,2,3,4];
let [a ,b,c,d] = arr;
at this time a = 1; b=2; c=3; d= 4;

2. More complex destructuring assignment

If we define a more complex array like the following line of code, how should we get the corresponding data?

const arr = ['a','b',['c','d',['e','f','g']]];

This is where we can remember the following points, namely

  1. Nestable
  2. Ignorable
  3. incomplete deconstruction
  4. remainder operator
  5. default value

For example, if we want to get b in the previous array, we can do it like this

const arr = ['a','b',['c','d',['e','f','g']]];
const [,b] = arr;

We got g in the previous array, we can operate like this

const arr = ['a','b',['c','d',['e','f','g']]];
const [,,[,,[,,g]]]=arr;

Remainder operator, the following code uses the remainder operator, also called the expansion operator. It
should be noted here that the remaining elements will be connected together in the form of an array in the original order.
The operator must be placed at the end, otherwise will report an error

const arr = ['a','b',['c','d',['e','f','g']]];
const [a,...b] = arr;

The result of the operation, b at this time

Insert image description here

About the default value of destructuring
1. When we destructuring and assigning values ​​to the array, if the number of variables is more than the number of elements of the original array, the extra variables will be directly copied to undefined
2. When the value corresponding to the variable is undfined The default value can be redefined.
For example,
const arr = [1, undefined, undefined];
const [a, b = 2, c, d="aaa"] = arr;
at this time, a, b, c, d correspond to 1, 2, undefined, "aaa";

incomplete deconstruction

let [a = 1, b] = []; // a = 1, b = undefined

Guess you like

Origin blog.csdn.net/m0_56026872/article/details/118253961