Before we get into that, let’s take a look at what deconstruction assignment is. From the analysis of the phrase, we can roughly understand that deconstruction – that is, to destroy, to destroy the original structure, to assign – of course, to assign again. Let’s take a look at what deconstruction assignment is.

Destruct assignment of arrays

1. Basic usage

ES6 allows you to extract values from arrays and objects in a pattern and then assign values to variables, which is called Destructuring. Previously, assigning a value to a variable could only specify a value directly.

let a = 1;
let b = 2;
let c = 3;
Copy the code

ES6 allows me to write it like this.

let [a,b,c] = [1.2.3]
Copy the code

The above code shows that you can extract values from an array and assign variables to their positions. Essentially, this is “pattern matching,” in which the variable on the left is assigned a corresponding value as long as the pattern on both sides of the equal sign is the same. Here are some examples of destructuring using nested arrays.

 let [foo, [[bar], baz]] = [1The [[2].3]];
 foo / / 1.
 bar / / 2;
 baz / / 3;
 
 let [ , , third] = ["foo"."bar"."baz"];
 third //"baz"
 
 let [x,  , z] = [1.2.3];
 x / / 1
 z / / 3
 
 let [head, ...tail] = [1.2.3.4];
 head / / 1
 tail / / / 2 and 4
 
 let [x, y, ...z] = ["a"];
 x //"a"
 y // undefined
 z / / []
Copy the code

If the deconstruction fails, the value of the variable is equal to undefined.

let [foo] = [];
let [bar, foo] = [1];
Copy the code

The other case is incomplete deconstruction, where the pattern to the left of the equals sign matches only part of the array to the right of the equals sign. In this case, deconstruction can still succeed.

let [x, y] = [1.2.3];
 x / / 1.
 y / / 2;
 
 let [a, [b], c] = [1[1.3].4];
 a / / 1
 b / / 1
 c / / 4
Copy the code

The above example is incomplete deconstruction, but it can work. An error will be reported if the right-hand side of the equals sign is not an array, which is technically a non-traversal structure.

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

The above statement is an error because the value to the right of the equals sign either does not have an Iterator interface when converted to an object or does not have an Iterator interface. (Last expression) A quick introduction to the Iterator interface. Iterator is an interface that provides a unified access mechanism for a variety of data structures. Any data structure can be iterated as long as the Iterator interface is deployed. The following data structures have a native Iterator interface. You can use for… The of method loops through)

  • Array
  • Map
  • Set
  • String
  • TypedArray
  • The arguments object for the function
  • The NodeList object

2. Deconstructive assignment of Set and Map structures

let [x,y,z] = new Set(["a"."b"."c"]);
x// "a"
var map = new Map(a); map.set("first"."hello");
map.set("second"."world");
for(let [key, value] of map){
    console.log(key +" is " + value);
}
Copy the code

3. The default value

Destruct assignment allows you to specify default values.

let [foo = true] = [];
foo //true

let [x,y = 'b'] = ['a'];
x //'a';
y //'b';

let [x, y = 'b'] = ['a'.undefined];
x // 'a'
y // 'b'
Copy the code

ES6 internally uses the strict equality operator (===) to determine whether a position has a value. So, if an array member is not strictly equal to undefined, the default does not take effect.

let [x = 1] = [undefined];
x / / 1
let [x = 1] = [null];
x //null
Copy the code

The second example above does not take the default value because NULL does not exactly equal undefined. Also, note that the default value can refer to another variable in the deconstructed assignment, but that variable must already be declared.

let [x = 1, y = x] = []; //x =1 y = 1
let [x = 1, y = x] = [2]; // x = 2 y = 2
let [x = 1, y = x] = [1.2]; // x = 1 y = 2 
let [x = y, y = 1] = [];  //ReferenceError
Copy the code

The last error is because y has not been declared when x uses the default value.

Object destructuring assignment

Destruct assignment can be applied to objects as well as arrays.

let {foo, bar} = {foo:"aaa".bar: "bbb"};
foo // "aaa"
bar // "bbb"
Copy the code

The difference from an array

Deconstructed assignment of objects differs from arrays in one important way. The elements of an array are arranged in order, and the value of a variable is determined by its position. The attributes of an object have no order, and the variables must have the same name as the attributes to get the correct value

let {foo, bar} = {bar: "bbb".foo:"aaa"};
foo // "aaa"
bar // "bbb"
let {baz} = {bar: "bbb".foo:"aaa"};
baz //undefined
Copy the code

The above code verifies that the value is independent of the order. The second example does not get a value because the variable has no corresponding property of the same name, so it cannot get a value and finally equals undefined. If the variable does not match the attribute name, it must be written as follows,

let {foo:baz} = {bar: "bbb".foo:"aaa"};
baz //"aaa"

let obj = {first: "hello".last: "world"};
let {firt: f, last: l} = obj;
f // "hello"
l // "world"
Copy the code

The point is, in fact, that deconstructed assignment of an object is shorthand for the following

 let {foo: foo, bar: bar} = {foo:"aaa".bar: "bbb"};
Copy the code

The alias

That is, the internal mechanism for deconstructing assignment of an object is to find the property of the same name and then assign it to the corresponding variable. It is the latter, not the former, that is really assigned.

 let {foo:baz} = {bar: "bbb".foo:"aaa"};
 baz //"aaa"
 foo // foo is not defined
Copy the code
In the code above, ***foo is the matching pattern and baz is the variable. It is the variable baz that is actually assigned, not the pattern foo. *** Like arrays, deconstruction can also be used for objects with nested structures.Copy the code
 let obj = {
    p: ['hello',
       {y: 'world'}};let {p: [x,{y}]} = obj;
  x // "hello"
  y // "world"
Copy the code

Notice that p is a mode, not a variable, so it can’t be assigned. If p were to be assigned as a variable, it could be written like this,

  let obj = {
      p: ['hello',
          {y: 'world'}};let {p,p: [x,{y}]} = obj;
   x // "hello"
   y // "world"
   p // p:['hello', {y: 'world'}]
Copy the code

Another example,

  var node = {
     loc: {start : {
             line: 1.column: 5}}};var {loc, loc:{start}, loc: {start: {line}}} = node;
 line / / 1
 loc // Object {start : Object }
 start // Object {line: 1, column:5}
Copy the code

The above code has three deconstruction assignments, respectively for loc, start, and line. Note that in the last deconstruction assignment of the line property, only line was a variable, and both LOc and start were modes.

Object to assign to a variable

Be careful when assigning to a declared variable.

// Error
  let x
  {x} = {x:1};
//syntaxError: syntax error
Copy the code

The code above reports an error because the JavaScript engine interprets {x} as a block of code, resulting in a pre-error. As long as you don’t put {} on the first line, you’ll solve the problem.

let {x} = {x:1};
/ / or
let x;
({x} = {x:1})
/ / can also
{(x) = {x:1}}
Copy the code

As for the use of parentheses, the rule is not to misuse them. Please refer to ruan yifeng es6 standards, very comprehensive! So to summarize,

Destruct assignment of a string

example

const [a,b,c,d,e] = 'hello'
Copy the code

Numeric and Boolean type destruct assignment

When deconstructing an assignment, if the value and Boolean are to the right of the equals sign, the object is converted first.

let {toString : s} = 123;
s === Number.prototype.toString //true
let {toString : s} = true;
s === Boolean.prototype.toString //true
Copy the code

In the code above, the wrapper objects for both numbers and booleans have toString attributes, so the variable S can take on a value. The rule for deconstructing assignment is that if the value to the right of the equals sign is not an object or array, it will be converted to an object first. Undefined and NULL cannot be converted to an object, so an error will be reported when deconstructing assignment.

use

Swap the values of variables

  //ES5
  var t;
  t = a;
  a = b;
  b = t;

 //ES6
 let x = 1;
 let y = 2;
 [x, y] = [y, x];
Copy the code

Returns multiple values from a function

A function can only return one value. If you want to return multiple values, you have to put them in an array or an object.

  // Return an array
  function example() {
    return [1.2.3.4]}let [a,b,c,d] = example();
 // If the assignment is not destructed, the assignment must be iterated separately.
 
 // Return an object
  function example() {
    return {
        foo: 1.bar: 2
    };
  }
  let {foo, bar} = example();
Copy the code

Definition of function parameters

Deconstructing assignments makes it easy to map a set of parameters to variables

  // Arguments are an ordered set of values
  function f([x,y,z]) {}
  f([1.2.3])
  // Arguments are an ordered set of values
  function f({x,y,z}) {}
  f({x:1.z:2.x:3});
Copy the code

Extract data from JSON

 let jsonData = {
    id:23.state:"draft".data: {name:"hansheng".age: 18}}let {id,state,data:info} = jsonData;
  // 23,"draft", {name:"hansheng",age: 18}
Copy the code

This article extracts from ruan Yifeng ES6 standard introduction.