Reference articles: Rookie Tutorial, Introduction to ECMAScript 6 (Ruan Yifeng)

Definition of deconstruction

ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern known as deconstruction.

Composition of a structure expression

1. Destruct source: the source of the destruct expression value, the right side of the expression. 2. Destruct target: The storage variable that defines the destruct expression value, the left side of the expression

Array deconstruction

Basic usage
let[a, b, c] = [1, 2, 3]. console.log(a); \\ 1 console.log(b); \\ 2 console.log(c); \ \ 3Copy the code

As long as the structure of the expression is the same, and the corresponding variable on the left can find the corresponding value on the right, the value on the right can be assigned to the variable on the left. We can use deconstructed assignment to simplify the data passed to us from the background and reduce the number of data traversal loops

Can be nested
let [a, [[b], c]] = [1, [[2], 3]];
// a = 1
// b = 2
// c = 3
Copy the code

If the above variable b is not enclosed by [], then b returns the value with brackets as follows:

let [a, [b, c]] = [1, [[2], 3]];
// a = 1
// b = [2]
// c = 3
Copy the code
Can be ignored
let [a, , b] = [1, 2, 3];
// a = 1
// b = 3
Copy the code

If the ignored item is at the end, it is directly ignored. If the ignored item is not at the end, fill it with a comma (,). If the comma (,) is omitted, the browser completes it at the end by default. For example:

let [a, , b] = [1, 2, 3, 4];
// a = 1
// b = 3

let [a, , , b] = [1, 2, 3, 4];
// a = 1
// b = 4
Copy the code
Incomplete deconstruction
let [a = 1, b] = []; 
// a = 1
// b = undefined
Copy the code

If the defined variable has no corresponding term on the right, it is assigned: undefined; If the defined variable is given a default value and the matching result is undefined, the deconstructed result is the default value.

Residual operator
let [a, ...b] = [1, 2, 3];
//a = 1
//b = [2, 3]
Copy the code

Note: Expressions with residual operator items are placed last

The structure source is a string
let [a,b,c] = "ES6"
// a = "E"
// b = "S"
// c = "6"
Copy the code
Deconstructing defaults

When the deconstruction pattern has a match, and the match is undefined, the default value is triggered as the return result.

let [a = 3, b = a] = [undefined];     // a = 3, b = 3
let [a = 3, b = a] = [1];    // a = 1, b = 1
let [a = 3, b = a] = [1, 2]; // a = 1, b = 2
Copy the code

If a =a, b= 3, c = 3, c = 3, d = 3, d = 3, d = 3, d = 3, d = 3, d = 3, d = 3, d = 3, d = 3, d = 3, d = 3, d = 3 The second expression a matches 1, so return a match 1, b matches undefined, so return b default value, b default value b=a,a is 1, so b is 1; The third expression a matches 1, so returns a match value 1, b matches 2, so returns b match value 2;

The deconstruction match value is NULL
let [a=12] = [null]
// a = null
Copy the code
Deconstructing Set
let [a, c, c] = new Set(['a'.'b'.'c']);
//  a = "a"
//  b = "b"
//  c = "c"
Copy the code

Structures that cannot be traversed cannot be deconstructed, for example:

let [a] = 1;
let [a] = false;
let [a] = NaN;
let [a] = undefined;
let [a] = null;
let [a] = {};
Copy the code

All of the above code will return an error after the browser executes.

Deconstruction of the object model

basic
let {name,age} = {name:"Zhang",age:20}
// name = "Zhang"
// age = 20
Copy the code

Note: The variable name on the left of the equal sign here is the abbreviation of name:name, and age is the abbreviation of age:age. The new feature of ES6 stipulates that the attribute and value of an object can be shortened to one with the same variable. So: the result of the structure is actually a deconstruction of the variable assigned to the object property value ######

let {name:name1} = {name:"Bill"} // name = undefined(name is not defined) // name1 ="Bill"
Copy the code

As you can see from the above code, the result of the deconstruction is assigned to the variable corresponding to the object attribute value

Can be nested
let {p: [x, { y }] } = {p: ['hello', {y: 'world'}}; // x ='hello'
// y = 'world'
Copy the code
Can be ignored
let {p: [x, {  }] } = {p: ['hello', {y: 'world'}}; // x ='hello'
let {p: [, { y }] } = {p: ['hello', {y: 'world'}}; // y ='world'
Copy the code
Incomplete deconstruction
let {p: [{ y }, x ] } ={p: [{y: 'world'}}; // x = undefined // y ='world'
Copy the code
Residual operator
let{a, b, ... rest } = {a:"Zhang", b: "Bill", c: "Fifty", d: "Li Er"};
// a =  "Zhang"
// b = "Bill"
// rest = {c: "Fifty", d: "Li Er"}
Copy the code
Deconstructing defaults
let {a = 1, b = 2} = {a: 3};
// a = 3; b = 2;
let {a: aa = 10, b: bb = 5} = {a: 3};
// aa = 3; bb = 5; 
Copy the code

The default destruct value is triggered when the result of the match is undefined.

Variables that have been declared are used to deconstruct assignments

// This is not the caselet x;
{x} = {x: 1};
// Uncaught SyntaxError: Unexpected token '='
Copy the code

This code is an error because the browser parses the braces into blocks with either Spaces or “; “between them. , so an error is reported. The solution is to convert it to an expression with ()

let x;
({x} = {x: 1});
Copy the code

Application scenarios

1. Sum any parameters

Traditional methods: js Traditional methods need to use arguments to implement, specific methods as follows:

function sum(){ var sum = 0; var len = arguments.length; // Storing the length in variables can reduce the number of loops and improve performancefor(var i = 0; i < len; i++){ sum +=arguments[i] }returnsum; } the sum (1, 2, 3); / / 6 sum (1, 2,"4"); // "34"
Copy the code

This is just a comparison between the traditional method and the new ES6 method summation, no numeric type conversion, so the second call appears string concatenation

ES6 new method: ES6 uses residual expression and deconstruction to store the number of parameters. The sum method is as follows:

functionsum(... nums){let sum = nums.reduce((x,y)=>{return x+y})
  returnThe sum} sum (1, 2, 3); / / 6 sum (1, 2,"4"); // "34"
Copy the code

Note the new method used for the ES6 array: Reduce, reduce is used to summarize, input a bunch, output a result. It may feel like the implementation principle of the two methods is the same. The traditional method uses an array of classes, although we can use subscripts like arrays. Namely the arguments [0], the arguments [1],… You can also use arguments.length to count the number of arguments passed. You can also use arguments.callee(note that this attribute is deprecated in ES5 as caller is not an attribute). Such as reduce, pop, a push, shift, unshift, etc., with the traditional methods for parameter and so more often than ES6 code for several lines.

2. Swap values of variables without a third argument

Traditional methods: Traditional methods (before ES6, C language, etc.) to exchange the values of two variables need to use a third variable, in JS implementation method is roughly as follows:

let a = 1;
let b = 2;
let c = a;
console.log(a,b,c);
a = b;
b = c;
// a = 2;
// b = 1;
// c = 1;
Copy the code

So the traditional approach takes about five lines of code to implement.

ES6 method: we do not need to use the third parameter in ES6, specific implementation method is as follows:

let a = 1;
let b = 2;
[a, b] = [b, a];
// a = 2;
// b = 1;
Copy the code

You can see from the above that we only need three lines of code to do this.

3. Collect the remaining parameters of the function and use them as public function options

We all know that arguments passed in JS can not correspond to one and one; If the number of parameters is greater than the number of arguments, the extra parameters are initialized as undefined. When the number of parameters is smaller than the number of arguments, the extra arguments are ignored. Therefore, in some scenarios, parameters that we only use once or may not use will be passed by defining parameters. In some scenarios, the number of parameters is uncertain and we can only solve the problem by defining multiple parameters, but this is obviously a bit awkward. In the new ES6 features, we can use the “… + variable name “to solve the problem of parameter passing. We can use a function to model the API’s optional parameters simply by putting the required parameters in front and the optional parameters in the remaining items, so our code looks like this:

functiondateFormat(a,.. b){ ... }Copy the code

The code above shows that a is a mandatory parameter and b is a set of optional parameters, so that we can use a variable to put uncommon parameters into a set.

4. Return multiple function results

Before ES6, we wanted to return multiple results from a function. We could only return them in arrays or objects. To retrieve each result, we had to loop and iterate, which was a headache. With ES6 we can extract the results of function execution one by one. The approximate code is as follows:

// Return an arrayfunction test() {
  return [1, 2, 3];
}
let [a, b, c] = test(a); // Return an objectfunction test() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = test(a);Copy the code
5. Simplify calls to underlying data

A lot of times we are returned with a mixture of objects and arrays nested in the background, and we often need to write a long string of “” for deep data access. Using deconstruction assignment we can extract these data separately.

6. Set default values for function parameters
jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
} = {}) {
  // ... do stuff
};
Copy the code

The default value of the specified argument, avoids the within the function body to write var foo = config. The foo | | ‘default foo’; Statement like this.

7. Traverse the Map structure

You can use for any object that has the Iterator interface deployed. The of loop traverses. The Map structure natively supports the Iterator interface, and it is very convenient to obtain key names and values along with the deconstructive assignment of variables.

const map = new Map();
map.set('first'.'hello');
map.set('second'.'world');

for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world
Copy the code

If you just want to get the key name, or if you just want to get the key value, you can write it like this.

// Get the key namefor (let[key] of map) { // ... } // get the key valuefor (let [,value] of map) {
  // ...
}
Copy the code
8. Input the specified method of the module

When a module is loaded, it is often necessary to specify which methods to input. Deconstructing assignment makes the input statement very clear.

const { SourceMapConsumer, SourceNode } = require("source-map");
Copy the code

Note: This article references cainiao tutorial and Ruan Yifeng’s blog post