• An array of deconstruction

Extract from the array index

Const arr = [1,2,3] const [foo,bar,baz] = arr // const [, baz] = arr // const [foo,...rest] = arr // The last member uses, Const [foo] = arr // Infully destructs const [foo,bar,baz,more...bao] = arr //more undefined,bao=[] const [foo,bar,baz,more="10",] = arr

An error will be reported if the right-hand side is not a traversable Iterator

let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
  • The default value takes effect when an array member is strictly equal to undefined

    let [x = 1] = [undefined];         x // 1
    
    let [x = 1] = [null];              x // null
  • Object deconstruction Array deconstruction is based on subscript order, object deconstruction is based on attribute name matching extraction, it has no order

    const obj = {name:'mcgee',age:18}
    const { age,name,baz } = obj
    console.log(name); //'mcgee'
    console.log(baz);  //undefined

    Deconstructive assignment of an object. It is easy to assign methods of an existing object to a variable

    Const {log} = console //log is the console property log("foo") let {floor,ceil} = Math

    A member with the same name causes a naming conflict

    const name = "jack" const {name} = obj console.log(name); Const name = "jack" const {name:objName} = obj // rename object name attribute console.log(name,objName);

    Set Default Values

    Const {name:objName="rose"} = obj // Set the default value for the name attribute console.log(objName)

    Pay attention to

Because the JavaScript engine interprets {x} as a block of code, syntax errors occur. You can solve this problem only by not writing curly braces at the beginning of the line and avoiding JavaScript interpreting them as blocks of code

let x;
{x} = {x: 1}; // SyntaxError: syntax error

let x;
({x} = {x: 1});

The expression is meaningless, but the syntax is legal and executable

({} = [true, false]);
({} = 'abc');
({} = []);

Other deconstruction

string

The string is converted to an array-like object

const [a, b, , , e] = 'hello'; a // "h" b // "e" e// "o" let {length : len} = 'hello'; // Array objects have the length attribute len // 5

The number and Boolean

If the right hand side of the equal sign is numeric and Boolean, it will be converted to an object first

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

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

Null, and undefined

let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError

Function parameter deconstruction

Deconstruction purposes

Variable exchange

The function returns multiple values

Function parameters

Default values for function parameters

Traverse the Map structure (Map is a key-value pair data structure)

The input module specifies the method

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