The introduction

Great oaks from little acorns rise, and you must first lay down the basic skills: programming languages always need variable assignment; ES6 introduced a new form of assignment: deconstructed assignment; Destruct assignment greatly simplifies variable assignment code. Destruct assignment can only be used for data that has iterators.

What is an Iterator? Here are two articles for reference (helpful for reading below) :

My own summary of iterator understanding

Geek Academy article written by Teacher Ruan Yifeng


Assignment and deconstruction assignment

In ES5, we assign values to variables like this

var a = {item: 'obj'.item1: 'obj1'},
    b = ['c1'.'c2'.'c3'],
    c = 'test',
    d = 'test2'
var item = b.item,
    item1 = b.item1,
    item2 = b.item2,
    arrItem = c[0],
    arrItem1 = c[1];
item;       //obj
item1;      //obj1
item2;      //undefined
arrItem;    //c1
arrItem1;   //c2
Copy the code

emmmmm… Use ES6 to destruct an assignment:

let a = {item: 'obj'.item1: 'obj1'},
    b = ['c1'.'c2'.'c3'];
let{item, arrItem1,arrItem2} = a, arrItem1 = b, arrItem2 = b; item;//obj
item1;      //obj1
item2;      //undefined
arrItem;    //c1
arrItem1;   //c2
arrItem2;   //c3
Copy the code

There is no harm without comparison. Deconstructing assignment can reduce the amount of code to a certain extent, and the form of code assignment is simple and intuitive. Destruct assignment applies not only to let but also to const and var.

Destruct assignment only allows objects to the right of the equals sign to be objects that have an Iterator. Here is an example of an incorrect deconstruction assignment:

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

Destruct assignment allows you to specify a default value for a variable when assigning.

//ES5
let obj = {item1: 'test'},
    item1 = obj.item1,
    item2 = obj.item2;
item2;      // An empty string
    
//ES6
let obj = {item1: 'test'},
    { item1=' ',item2=' ' } = obj;
item2;      // An empty string
Copy the code

By comparing the assignment form of ES5 with the deconstructed assignment of ES6, the variable Item2 in the assignment form of ES5 has undefined value due to the absence of item2 attribute in OBj, while the deconstructed assignment of ES6 can reserve default value for the variable during assignment. Avoid assigning variables to get the value of undefined; Its effect can be understood as

let item1 = obj.item1 || ' ',
    item2 = obj.item2 || ' ';
Copy the code

If a variable does not have a default value, the resulting value will also be undefined when deconstruction fails.

let obj = {a: 'string'},
    [b,c] = ['test'],
    {d} = obj;
b;      //test
c;      //undefined
d;      //undefined
Copy the code

The above situation is an example of some variables with deconstruction failure. Variable B corresponds to test,c has no corresponding value, obj.d does not exist, and C and D have no default value. Therefore, deconstruction of c and D fails, and the value obtained is undefined.

The default value takes effect only when the value of a variable is undefined

let a = {b: null},
   {b='test'} = a;
b;  // null
let [c='test'] = [undefined];
c;  //test
let [d='test',e='www'] = [NaN.null];
d;  //NaN
e;  //null
Copy the code

ES6 internally uses the strict equality character === to determine whether a value is undefined. The default value takes effect only when the value is undefined.

If the default value specified in a deconstructed assignment is a function expression, the expression will be evaluated if and only if it is used

let fn = (a)= > {
    return '123';
};
let [a=fn(),b=fn()] = [1];
a;      / / 1
b;      / / 123
Copy the code

In some cases, destruct assignment can also be used to call the methods of certain objects with simple names

let { assign, freeze } = Object;
let a = assign({},{b:1}),
    b = freeze(a);
a;      //{b: 1}
b;      //{b: 1}
Copy the code

When a variable that has been declared by a variable is used for destructuring assignment, the destructuring assignment expression needs to be placed inside ()

let a = 'test';
{a} = {a: 'obj test'};          // Uncaught SyntaxError: Unexpected token =
({a} = {a: 'obj test'});        //a equals obj test
Copy the code

This is because during JavaScript interpretation, if the line begins with “{“, JavaScript will interpret the code wrapped in “{}” as a code block, resulting in syntax errors. What we really need is {a} = {a: ‘obj test’}, so we need to wrap “()” around {at the beginning of the line.

When an object is destructively assigned, the variable name is not required to be the same as the attribute name, but the named assignment is slightly different

let man = {name:'john'.sex:'male'.height:'177cm'.weight:'70kg'.interest:'climbing'};
let {name: mans_name,sex:sexal,height:tall,job:works='u guess'} = man;
mans_name;      //john
sexal;          //male
tall;           //177cm
works;          //u guess
name;           //Uncaught ReferenceError: name is not defined
Copy the code

let {name: mans_name} = man; Mans_name = mans_name = mans_name = mans_name = mans_name = mans_name = mans_name

Destruct assignment applies to function parameters

function Human({name=' ',sex='female',age}) {
    if(sex==='male') {
        console.log('u must be a handsome guys! ');
    }else if(sex === 'female') {
        console.log('u must be a beauty! ');
    }else {
        console.log('exm,r u seriouse? ');
    }
    console.log(name);
    console.log(sex);
    console.log)(age);
}
let character = {sex:'male'.name:'Allen'.age:27}
Human(character); 
// u must be a handsome guys!
// Allen
// male
//  27
Copy the code

When the parameter is undefined, the default values will also take effect, such as the sex parameter. When no sex parameter is passed, the default value of sex will be female.

Destructuring assignments also applies to strings

let [a,b,c,d] = 'test',
a;          //t
b;          //e
c;          //s
d;          //t
Copy the code

If the value to the right of the equal sign is a string, the destruct assignment will convert the string to an array-like destruct for variable assignment. Array objects all have the length attribute, so objects like arrays must also have the length attribute. The following code block also performs the assignment successfully.

let {length: len} = 'test';
len;        / / 4
Copy the code

Destructively assign values to numeric and Boolean data

let {a,toString} = 123;
a;      //undefined
toString === Number.prototype.toString;      //true

let {b,toString} = true;
b;      //undefined
toString === Boolean.prototype.toString;     //true
Copy the code

In the above two examples, the value on the right can be objectified (Number, Boolean), and the toString attribute exists after objectification. Therefore, the toString variable is equivalent to the prototype.toString method after the corresponding right value is objectified. A and B are attributes that do not exist after objectification, so the value obtained is undefined.

The rule of deconstruction assignment is that if the object type is on the right side of the equal sign, the deconstruction assignment will be performed directly. If the object type is not the object type, the object type will be converted to the object type. Then the deconstruction assignment will be performed.


Deconstruct the multifunctional use of assignment

Deconstructing assignments simplifies variable exchange

let a = 1,b = 2;
[a,b] = [b,a];
a;          / / 2
b;          / / 1
Copy the code

Deconstructing assignment simplifies evaluating the return value of a function

function test() {
    return {a:'a'.b:'b'.c:'c'};
};
let {a,b,c} = test();
a;      //a
b;      //b
c;      //c
Copy the code

Deconstructed assignment simplifies key data acquisition and error tolerance writing of data assignment

let map = new Map(a); map.set('test'.'javacript').set('do'.'something');
for(let [key,value] of map) {
   console.log(key + ' ' + value);
}
//test javascript
//do something

let obj = {},
   {a='It was undefined, but now it has the value of this string.'} = obj;
a;     // It used to be undefined, but now it has the value of this string
Copy the code

Load specified methods or data on modules introduced by import or require

import {Ajax_Interface,Format_Interface} from '~/Interface_Configs.js';
const {RouterConfigs, PageConfigs} = require('Common-Configs');
Copy the code


Some summary of deconstruction assignment

ES6 provides deconstructed assignments that make assignments more readable by reserving default values for variables and avoiding errors caused by undefined during data operations. Deconstruction assignment is applied to function parameter processing to avoid the troublesome problem of parameter fetching caused by disordered input.

The above.

If there are mistakes in the content of the article, welcome to point out the exchange and mutual progress