5 JS interesting use of deconstruction

Abstract: Fun ES6 deconstruction assignment.

1. exchange variables

The method usually requires an exchange of two variables additional temporary variables to look at an example:

    let a = 1;
    let b = 2;
    let temp;
    
    temp = a;
    a = b;
    b = temp;
    
    a; // => 2
    b; // => 1

tempIs a temporary variable, it first save avalue. Then bthe value is assigned to a, and then the tempvalue is assigned b.

If you use a deconstructed way will be more simple, what the hell do not need tempvariable.

    let a = 1;
    let b = 2;
    
    [a, b] = [b, a];
    
    a; // => 2
    b; // => 1

[a,b] = [b,a]Deconstruction assignment, right, create an array [b, a], that is [2,1]. This array 2is assigned a given a, is assigned to the 1 b.

Although this approach also creates a temporary array, but at least this way to look cleaner, you can also use deconstruction exchange 2more than one variable.

    let zero = 2;
    let one = 1;
    let two = 0;
    
    [zero, one, two] = [two, one, zero];
    
    zero; // => 0
    one;  // => 1
    two;  // => 2

2. Access the elements of the array

Kind of scenario, we may have an empty item in the array. And you want to access a first array, second or n-th item, but if the entry does not exist, a default value is specified.

Typically using an array of lengthproperty to determine

    const colors = [];
    
    let firstColor = 'white';
    if (colors.length > 0) {
     firstColor = colors[0];
    }
    
    firstColor; // => 'white'

Using arrays deconstruction can be more simple to achieve the same effect:

    const colors = [];
    
    const [firstColor = 'white'] = colors;
    
    firstColor; // => 'white'

const [firstColor = 'white'] = colorsDeconstructing the colorsfirst element of the array is assigned to firstColorthe variable. If the array index 0no elements at the assigned " white" default.

Of course, it can also be more flexible, if you only want to access the second element, you can do so.

    const colors = [];
    
    const [, secondColor = 'black'] = colors;
    
    secondColor; // => 'black'

Note the comma on the left side of deconstruction: it means to ignore the first element, secondColorusing colorsan array index 1assignment elements.

3. Operation immutable

When I started using Reactand Reduxwhen, forced to write some code to comply with immutability. Although at first some difficulties, but then I saw it benefits: easier to handle unidirectional data flow.

Invariance requirements can not change the original object. Fortunately, deconstruction can be changed in a manner not easily achieve certain operations.

    const numbers = [1, 2, 3];
    
    const [, ...fooNumbers] = numbers;
    
    fooNumbers; // => [2, 3]
    numbers; // => [1, 2, 3]

Deconstruction [, ... fooNumbers] = numberscreate a new array fooNumbers, fooNumberscontaining numberselements in addition to the first element.

numbers The array does not change, keep the operation invariance.

In the same manner immutable object can be deleted from the properties, from the object and then try to bigremove the fooproperties:

    const big = {
     foo: 'value Foo',
     bar: 'value Bar'
    };
    
    const { foo, ...small } = big;
    
    small; // => { bar: 'value Bar' }
    big; // => { foo: 'value Foo', bar: 'value Bar' }

4. deconstruction iterables

In the first few cases, the use of an array of deconstruction, but it can achieve any may iterate Protocol (iterable protocol) deconstruction object.

Many native primitive types and objects are iterable: array, string, typed arrays, setand map.

If you do not want to be limited to basic types, can be achieved through an iterative protocol can be customized deconstruction logic.

moviesIt contains a movielist of objects. Deconstruction movies, it will titleobtain is great as a character string. Let's implement a custom iterator.

    const movies = {
      list: [
        { title: 'Heat' }, 
        { title: 'Interstellar' }
      ],
      [Symbol.iterator]() {
        let index = 0;
        return {
          next: () => {
            if (index < this.list.length) {
              const value = this.list[index++].title;
              return { value, done: false };
            }
            return { done: true };
          }
        };
      }
    };
    
    const [firstMovieTitle] = movies;
    console.log(firstMovieTitle); // => 'Heat'

moviesBy defining the object Symbol.iteratorto achieve agreement iterative method is iterating title.

Follow iterable protocol allows the moviesobject into titlethe specific method is to read the first moviesof title: const [firstMovieTitle] = movies.

The dynamic properties deconstruction

According to experience, deconstruction is more common than the deconstruction of an array of objects through the property.

Deconstruction of the object looks more simple:

    const movie = { title: 'Heat' };
    
    const { title } = movie;
    
    title; // => 'Heat'

const {title} = movieCreate a variable title, property and movie.titleassign it value.

When the object is to deconstruct, I was a little surprised that we still do not have to know the name of a property can use the dynamic attribute names to deconstruct objects.

In order to understand the dynamics of how the work of deconstruction, write a greetfunction:

    function greet(obj, nameProp) {
     const { [nameProp]: name = 'Unknown' } = obj;
     return `Hello, ${name}!`;
    }
    
    greet({ name: 'Batman' }, 'name'); // => 'Hello, Batman!'
    greet({ }, 'name'); // => 'Hello, Unknown!'

Use 2a parameter called greet()function: object and attribute names.

In greet()the interior, destructuring assignment const {[nameProp]:name ='Unknown'} = objusing square brackets in the form of [nameProp]reading a dynamic attribute name, namevariable receives the dynamic attribute values.

Better yet, if the property does not exist, you can specify a default value of " Unknown."

After the code is deployed may exist BUG can not know in real time, and afterwards in order to solve these BUG, we spent a lot of time debugging log, here the way for everyone to recommend a nice BUG monitoring tools Fundebug .

Original: https://dmitripavlutin.com/5-interesting-uses-javascript-destructuring/

About Fundebug

Fundebug focus on JavaScript, applets micro-channel, micro-channel games, Alipay small program, React Native, Node.js and Java applications in real-time online monitoring BUG. Since 2016, two-eleven formally launched, Fundebug handled a total of 2 billion + error event, paying customers have Sunshine Insurance, walnut programming, lychee FM, head of the 1-to-1, micro pulse, the Youth League and many other community brands. Welcome to Free Trial !

Guess you like

Origin www.cnblogs.com/fundebug/p/5-interesting-uses-javascript-destructuring.html