Array structure assignment

1. Basic usage

ES6 allows you to extract values from arrays and objects in a pattern and then assign values to variables. This is called deconstructed assignment.

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

Now that we’ve upgraded, we can write it this way!

Let [a, b, c] = [1, 2, 3].Copy the code

The code ↑ shows that we can extract values from the array and assign values to the corresponding variables. This is essentially a matching pattern. As long as the pattern on both sides of the equal sign is the same, the variable on the left will be assigned the value of the corresponding position. Here are some examples:

  1. Completely deconstruct chestnuts
let [a,[b],c] = [1,[2],3]; console.log(a,b,c); // let [x, y] = [1,2,3]; console.log(x,y); // 1 3 let [head,...tail] = [1,2,3,4]; console.log(head,tail); // 1 [2,3,4] let [x,y...z] = ['a']; console.log(x,y,z); // 'a' undefined [] // If destruct fails, the value of the variable is undefinedCopy the code
  1. Incomplete deconstruction chestnut (pattern jobs on the left of the equals sign match part of the array on the right of the equals sign, but can still be deconstructed successfully)
Let (x, y) = [1, 2, 3]. console.log(x,y); // 1 2 let [a,[b],c] = [1,[2,3]; console.log(a,b,c); 4/1/2Copy the code
  1. Can’t deconstruct chestnuts
let [a] = 1; let [a] = false; let [a] = NaN; let [a] = undefined; let [a] = null; let [a] = {}; // All the above statements will fail because the value to the right of the equals sign does not have an Iterator interface itself or when converted to an object does not have an Iterator interfaceCopy the code

For Set deconstruction, you can also use array deconstruction assignment!

    let [x,y,z] = new Set('a','b','c');
    console.log(x); // a
Copy the code

2. The default value

Look at a piece of code

let [a = true] = []; console.log(a); Let [x, y = 'b'] = ['a']; let [x, y = 'b']; // x = 'a' y = 'b'Copy the code

Let’s look at another piece of code

    let [x = 1] = [undefined];
    let [y = 1] = [null];
    console.log(x,y); // 1 null
Copy the code

Why is that? Because ES6 uses the strict equality symbol (===) to determine whether a position has a value, the default does not take effect if an array member is not strictly equal to undefined. Because null does not exactly equal undefined, the default does not take effect.

Default values can refer to other variables that are destructively assigned, but the variables must already be declared

let [x=1,y=x] = []; // x=1; y=1 let [x=1,y=x] = [2]; // x=2; Let [x=1,y=x] = [1,2]; // x=1; y=2 let [x=y,y=1] = []; // ReferenceErrorCopy the code

Object destructuring assignment

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

    let {foo,bar} = {foo:'aaa',bar:'bbb'};
    console.log(foo,bar); // 'aaa' 'bbb'
Copy the code

The structure of objects differs from that of 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 {baz} = {foo:'a',bar:'b'};
    conosle.log(baz); // undefined
    
    let {foo:baz} = {foo:'a',bar:'b'}
    console.log(baz); // a 
    
    let obj = {a:'a',b:'b'};
    let {a:aa,b:bb} = obj;
    console.log(aa,bb); // 'a' 'b'
Copy the code

In fact, object structure assignment is shorthand for the following form!

let {a:a,b:b} = {a:'aaa',b:'bbb'};
Copy the code

So the internal mechanism of object deconstruction assignment is to find the property of the same name and then assign the value to the corresponding variable. It’s the latter that gets assigned.

Destruct assignment of a string

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

    const [a,b,c,d,e] = 'hello';
    console.log(a,b,c,d,e); // h e l l o 
Copy the code

Array-like objects have a length attribute, so you can also destruct this attribute

let {length:len} = 'hello'; console.log(len); / / 5Copy the code

Numeric and Boolean structure assignments

When a structure is assigned a value or Boolean to the right of the equals sign, it is converted to an object 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, both the numeric and boolean-wrapped objects have toString attributes, so the variable S can take a value. The rule for deconstructing assignment is to turn the value to the right of the equals sign into an object whenever it is not an object or array. Because undefined and NULL cannot be converted to objects, they both report errors when destructively assigned.

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

Structure assignment of function arguments

function add([x,y]){ return x + y; } the add ([1, 2]); / / 3Copy the code

Parenthesis problem

While structure assignment is convenient, it is not easy to parse. There is no way for the compiler to know from the start whether an expression is a pattern or an expression. It must be parsed to (or not) the equals sign. This raises the question of what to do if parentheses are present in the schema! The rule of ES6 is that parentheses should not be used where they could lead to ambiguity in the structure.

use

1. Swap variable values

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

The above code swaps the values of variables x and y, which is very clear!

2. Return multiple values from a function

Function fn() {return [1,2,3]; } let [a,b,c] = fn(); Function fn() {return {foo :1, bar:2}} let {foo,bar} = fn();Copy the code

3. Definition of function parameters

Function fn([x,y,z]){function fn([x,y,z]){... } fn ([1, 2, 3]); Function fn({x,y,z}){... function fn({x,y,z}){... } fn({z:1,x:3,y:})Copy the code

4. Extract JSON data

Let jsonData = {id: 42, status: 'OK', data: [1,2]} let {id,status,data:number} = jsonData; console.log(id,status,data:number); / / 42 OK [1, 2]Copy the code

5. Traverse the Map structure

    var 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

6. Formulation method of input module

When loading modules, often need to specify the input method, structure assignment makes the input statement very clear ~

    const {aFun,bFun} = require('c');
Copy the code