Home>Article>Web Front-end> 5 ways to use destructuring in JavaScript

5 ways to use destructuring in JavaScript

青灯夜游
青灯夜游 forward
2020-11-30 18:00:08 8590browse

5 ways to use destructuring in JavaScript

Reading object properties and accessing array items are common operations. Destroying allocations makes these operations easier and cleaner. In this article, in addition to the basic usage, I will also introduce 5 interesting uses of destructuring in JavaScript.

1. Exchange variables

Usually the method of exchanging two variables requires an additional temporary variable. Let’s take a look at the example:

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

tempis a temporary variable, which first saves the value ofa. Then assign the value ofbtoa, and then assign the value oftemptob.

It will be simpler if you use destructuring, there is no need for any crazytempvariables.

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

[a, b] = [b, a]is a destructuring assignment. On the right, an array[b, a]is created, that is,[2,1]. This array2is assigned toa, and 1 is assigned tob.

Although this method also creates a temporary array, this method looks at least more concise. Using destructuring, we can also exchange more than2variables.

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

2. Accessing elements in the array

There is a scenario where we may have an empty item array. and want to access the first, second, or nth item of an array, but if the item does not exist, use the specified default value.

Usually thelengthattribute of the array is used to determine

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

Using array destructuring, the same effect can be achieved more concisely:

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

const [firstColor = 'white'] = colorsDestructuring assigns the first element of thecolorsarray to thefirstColorvariable. If the array does not have any elements at index0, the "white" default value is assigned.

Of course it can be more flexible. If you only want to access the second element, you can do this.

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

Note the comma on the left side of the deconstruction: it means to ignore the first element,secondColoruse the element with index1in thecolorsarray Make an assignment.

3. Immutable operations

When I started usingReactandRedux, I was forced to write some compliance Immutable code. Although it was a bit difficult at first, I later saw its benefits: it was easier to handle one-way data flow.

Immutability requires that the original object cannot be changed. Fortunately, destructuring makes it easy to implement certain operations in an immutable way.

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

Destructuring[, ... fooNumbers] = numbersCreates a new arrayfooNumbers,fooNumberscontainingnumberselements, except the first element.

numbersThe array has not changed and the operation remains unchanged.

In the same immutable way, you can delete attributes from the object, and then try to delete thefooattribute from the objectbig:

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

4. Destructuring iterables

In the previous examples, destructuring was used for arrays, but we can destructure any object that implements the iterable protocol.

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

If you don’t want to be limited to basic types, you can customize the destructuring logic by implementing the iterable protocol.

moviesContains a list ofmovieobjects. It's great to gettitleas a string when deconstructingmovies. 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'

moviesThe object implements the iterable protocol by defining theSymbol.iteratormethod, and the iterator iteratestitle.

Follows theiterable protocolallowsmoviesobjects to be decomposed intotitleby reading the firstmoviesThetitle:const [firstMovieTitle] = movies.

5. Destructuring dynamic properties

As a rule of thumb, object destructuring through properties is more common than array destructuring.

The destructuring of the object looks very simple:

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

const {title} = movieCreate a variabletitleand set the attribute ## The value of #movie.titleis assigned to it.

When it comes to object destructuring, I was a little surprised that we don’t have to know the property names statically and can use dynamic property names to deconstruct the object.

To understand how dynamic destructuring works, 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!'
Call

greet()# with2arguments ## Functions: object and property names.Inside

greet()

, destructuring assignmentconst {[nameProp]:name ='Unknown'} = objUse the form of square brackets[nameProp ]Read the dynamic attribute name, and thenamevariable receives the dynamic attribute value.A better approach is to specify a default value of "

Unknown

" if the property does not exist.

6. Conclusion

Destruction is very useful if you want to access object properties and array items.

In addition to basic usage, array destructor can also conveniently exchange variables, access array items, and perform some immutable operations.

JavaScript offers greater possibilities, as you can define custom destruction logic using iterators.

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

For more programming-related knowledge, please visit: programminglearning! !

The above is the detailed content of 5 ways to use destructuring in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:dmitripavlutin.com. If there is any infringement, please contact admin@php.cn delete