1.1 Destruct assignment of arrays

1.1.1 Basic Usage:

Extract the value from the array by the position of the variable, assign the value to the variable, and as long as the pattern on both sides of the equal sign is the same, the variable on the left will be assigned the corresponding value. The value of the variable is undefined if the deconstruction fails.

// Simple examplelet[a, b, c] = [1, 2, 3]; / / nestedlet [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

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

let [x, , y] = [1, 2, 3];
x // 1
y // 3

let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]

let [x, y, ...z] = ['a'];
x // "a"Y // undefined z // [] // undefined z // [] // Not completely destructedlet [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
Copy the code

If the object to the right of the equals sign does not contain the Iterator interface or does not contain the Iterator interface, an error message is displayed

/ / an errorlet [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};

// set, maps can be assigned using arrays destructivelylet [x, y, z] = new Set(['a'.'b'.'c']);
x // "a"

let map = new Map([
  ['name'.'Joe'],
  ['title'.'Author']]);let [foo] = map;
console.log(foo);
Copy the code

1.1.2 Default Values It is possible to specify a default value. If the default value is an expression, the expression is lazy, that is, it is evaluated only when it is used.

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 [foo = true] = [];
foo // true

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

The default value can refer to another variable of 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: y is not defined
Copy the code

1.2 Object deconstruction assignment

1.2.1 Basic Usage

The attributes of the object have no order, and the variables must have the same name as the attributes. If the variable name does not exist in the attribute, deconstruction fails and the value is undefined.

let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"

let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined

Copy the code

Object deconstruction assignment, it is very convenient to assign the method of an existing object to a variable.

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

If the name of the variable is different from the name of the property inside the object, you must write the following form

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 } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined
Copy the code

Can be used to nest deconstructed objects. (Follow the rules: objects follow the variable names equal to the internal properties of the object, and arrays follow the positions assigned.)

let obj = {
  p: [
    'Hello',
    { y: 'World'}};let { p: [x, { y }] } = obj;
x // "Hello"
y // "World"

Copy the code

An error is reported if the deconstruction pattern is a nested object and the parent property of the child object does not exist

/ / an errorlet {foo: {bar}} = {baz: 'baz'};
Copy the code

The deconstructive assignment of an object can take inherited properties.

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

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

1.2.2 the default value

Object destruct assignment can specify a default value, which is valid only if the property of the object is strictly equal to undefined.

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"

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

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

1.2.3 attention

1. Be very careful if you use an already declared variable to destruct an assignment.

// This is not the caseletx; {x} = {x: 1}; // SyntaxError: syntax error // JavaScript engine will interpret {x} as a code block // the correct way to writelet x;
({x} = {x: 1});
Copy the code

2. Arrays are special objects in nature, so you can deconstruct the object properties of arrays.

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

1.3 Deconstruction and assignment of strings

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"
let {length : len} = 'hello';
len // 5
Copy the code

1.4 Deconstructive assignment of values and Boolean values

If the right side of the equals sign is a value and a Boolean value, it is converted to an object first, and the properties and methods of the Number object and Boolean object can be obtained. (As long as the value to the right of the equals sign is not an object or array, it is first converted to an object.)

let {toString: s} = 123;
s === Number.prototype.toString // true

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

1.5 Deconstructive assignment of function parameters

Function arguments can be destructively assigned, or they can use default values

function add([x, y=3]){
  returnx + y; } add([1]); / / 4Copy the code

1.6 Parentheses problem

Deconstructing assignments is easy to use, but the compiler is not easy to parse. There is no way to know from the start whether an expression is a pattern or an expression, until it has been parsed to an equal sign or no equal sign at all. In ES6, parentheses should not be used if they could lead to ambiguity.

1.6.1 Deconstructing the case where parentheses cannot be used in an assignment

  1. Variable declarations
// All errors are reportedlet [(a)] = [1];
let {x: (c)} = {};
let ({x: c}) = {};
let {(x: c)} = {};
let {(x): c} = {};
let { o: ({ p: p }) } = { o: { p: 2 } };
Copy the code
  1. Function arguments (also variable declarations)
// All errors are reportedfunction f([(z)]) { return z; }
function f([z,(x)]) { return x; }
Copy the code
  1. The mode of the assignment statement
{p: a}) = {p: 42}; ([a]) = [5]; [({ p: a }), { x: c }] = [{}, {}];Copy the code

1.6.2 Cases where parentheses can be used

Parentheses can be used for the non-schema part of an assignment statement

[(b)] = [3]; {p: (d)} = {}); // Correct [(parseint.prop)] = [3]; / / rightCopy the code

1.7 use

  1. Exchange variable value
let x = 1;
let y = 2;

[x, y] = [y, x];
Copy the code
  1. Returns multiple values from a function
// Return an objectfunction example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();
Copy the code
  1. Definition of function parameters
// Arguments are an ordered set of valuesfunctionf([x, y, z]) { ... } f([1, 2, 3]); // Arguments are an unordered set of valuesfunction f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

Copy the code
  1. Extracting JSON data
let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let{ id, status, data: number } = jsonData; console.log(id, status, number); / / 42,"OK", [867, 5309]
Copy the code
  1. Function parameter default value
function second({x, y = 2}) {
    console.log("x:"+x ,"y:"+ y);
}
second({}); // x:undefined y:2
second({x:100}); // x:100 y:2
second({x:100,y:200}); // x:100 y:200
Copy the code
  1. Traverse Map deconstruction
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
  1. Specifies the method of input module

In: Ruan Yifeng