Home>Article>Web Front-end> 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.
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
temp
is a temporary variable, which first saves the value ofa
. Then assign the value ofb
toa
, and then assign the value oftemp
tob
.
It will be simpler if you use destructuring, there is no need for any crazytemp
variables.
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 array2
is 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 than2
variables.
let zero = 2; let one = 1; let two = 0; [zero, one, two] = [two, one, zero]; zero; // => 0 one; // => 1 two; // => 2
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 thelength
attribute 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'] = colors
Destructuring assigns the first element of thecolors
array to thefirstColor
variable. 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,secondColor
use the element with index1
in thecolors
array Make an assignment.
When I started usingReact
andRedux
, 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] = numbers
Creates a new arrayfooNumbers
,fooNumbers
containingnumbers
elements, except the first element.
numbers
The 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 thefoo
attribute 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' }
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
,set
andmap
.
If you don’t want to be limited to basic types, you can customize the destructuring logic by implementing the iterable protocol.
movies
Contains a list ofmovie
objects. It's great to gettitle
as 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'
movies
The object implements the iterable protocol by defining theSymbol.iterator
method, and the iterator iteratestitle
.
Follows theiterable protocolallowsmovies
objects to be decomposed intotitle
by reading the firstmovies
Thetitle
:const [firstMovieTitle] = movies
.
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} = movie
Create a variabletitle
and set the attribute ## The value of #movie.titleis assigned to it.
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()# with2
arguments ## Functions: object and property names.Inside
, destructuring assignmentconst {[nameProp]:name ='Unknown'} = obj
Use the form of square brackets[nameProp ]
Read the dynamic attribute name, and thename
variable receives the dynamic attribute value.A better approach is to specify a default value of "
" if the property does not exist. 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! ! 6. Conclusion
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!