1. Array deconstruction assignment

1.1 Basic Usage

let [a,b,c] = [1.2.3] 

let [foo, [[bar], baz]] = [1The [[2].3]].// Complex assignment
foo / / 1
bar / / 2
baz / / 3

let [ , , third] = ["foo"."bar"."baz"];  // Automatic position matching
third // "baz"

let [head, ...tail] = [1.2.3.4]; // combine with extension operators
head / / 1
tail / / [2, 3, 4]

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

It is not just arrays that can be destructively assigned. Any object with an Iterator interface can be destructively assigned as follows:

// Use ES6 yeild to implement Fibonacci sequence
function* fibs() {
  let a = 0;
  let b = 1;
  while (true) {
    yielda; [a, b] = [b, a + b]; }}let [first, second, third, fourth, fifth, sixth] = fibs();
sixth / / 5
Copy the code

The default value of 1.2

Destructuring assignments 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

Note that ES6 internally uses the strict equality operator (===) to determine whether a position has a value. Therefore, the default value is valid only if an array member is strictly equal to undefined.

let [x = 1] = [undefined];
x / / 1

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

The second reason for this failure is null! = undefiend

Also note that the default value expression is lazy evaluation, as follows:

function f() {
  console.log('If assigned by default, execute f and print the line');
}

let [x = f()] = [1];

// Console has no output
Copy the code

In this case, since x can be evaluated in the first place, f will not be executed at all.

In addition, the default value can refer to another variable of the deconstructed assignment, but that variable must already be declared.

2. Object deconstruction assignment

2.1 Basic object deconstruction assignment

Pay attention to

For a deconstructed assignment of an object, the right-hand side of the equal sign must have the key-value form corresponding to the left-hand side

As shown in the figure below

! [image-20200707144027174](/Users/chenlei/Library/Application Support/typora-user-images/image-20200707144027174.png)

The same applies to method assignments

! [image-20200707144100039](/Users/chenlei/Library/Application Support/typora-user-images/image-20200707144100039.png)

The most basic object deconstruction

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

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 variables must have the same name as the attributes to get the correct value.

Object deconstruction is also a convenient way to assign values to existing methods.

/ / a
let { log, sin, cos } = Math; // Assign the Math method to the log sine and cosine variables

/ / two cases
const { log } = console;
log('hello') // hello
Copy the code

In special cases, if the variable name and attribute name need to be inconsistent, you can write it as follows.

let { foo: baz } = { foo: 'aaa'.bar: 'bbb' };  // Note that foo is a match pattern, baz is the variable, and baz is actually assigned
baz // "aaa"

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

Alternatively, complex nested objects can be implemented through deconstruction, as follows

let obj = {
  p: [
    'Hello',
    { y: 'World'}};let { p: [x, { y }] } = obj;  // in this case p is not assigned as a variable
x // "Hello"
y // "World"

let {p,p: [x,{y}]} = obj 
x // "Hello"
y // "World"
p // ["Hello,{y: "World"}"]
Copy the code

Example of a complex nested assignment

let obj = {};
let arr = [];

({ foo: obj.prop, bar: arr[0]} = {foo: 123.bar: true });

obj // {prop:123}
arr // [true]
Copy the code

In addition, when performing object deconstruction assignment, it is possible to obtain inherited attributes.

const obj1 = {};
const obj2 = { foo: 'bar' };
Object.setPrototypeOf(obj1, obj2);

const { foo } = obj1;
foo // "bar"
Copy the code

2.2 Object Assignment Default value Settings

var {x = 3} = {};
x / / 3

var {x, y = 5} = {x: 1};
x / / 1
y / / 5

var {x: y = 3} = {};
y / / 3

var {x: y = 3} = {x: 5};
y / / 5

var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"
Copy the code

The default value takes effect only if the object attribute value is strictly equal to (===) undefind

var {x = 3} = {x: undefined};
x / / 3

var {x = 3} = {x: null};
x // null
Copy the code

2.3 pay attention to the point

If you want to use an already declared variable to destruct an assignment, you must be very careful.

// This is not the case
let x;
{x} = {x: 1};
// SyntaxError: syntax error
Copy the code

The above code is written incorrectly because the JavaScript engine interprets {x} as a block of code, resulting in syntax errors. The only way to solve this problem is to not put curly braces at the beginning of the line and avoid JavaScript interpreting them as blocks of code.

// The correct way to write
let x;
({x} = {x: 1});
Copy the code

The above code puts the entire destruct assignment statement in parentheses and executes correctly. See below for the relationship between parentheses and deconstructed assignment.

(2) Destruct assignment allows no variable names to be placed in the pattern to the left of the equal sign. As a result, you can write really weird assignment expressions.

({} = [true.false]); (= {}'abc');
({} = []);
Copy the code

The above expression makes no sense, but the syntax is legal and can be executed.

(3) Because the nature of the array is a special object, so we can deconstruct the object attributes of the array.

let arr = [1.2.3];
let {0 : first, [arr.length - 1] : last} = arr;
first / / 1
last / / 3
Copy the code

The above code deconstructs the array object. [arr. Length-1] = 2; [arr. Length-1] = 3; Square brackets are “attribute name expressions” (see extension of Objects).

3. Destruct assignment of strings

Strings can also deconstruct assignments. This is because at this point, the string is converted to an array-like object.

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
Copy the code

Array-like objects have a length attribute, so you can also deconstruct and assign to this attribute.

let {length : len} = 'hello';
len / / 5
Copy the code