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 of a
. Then assign the value of b
to a
, and then assign the value of temp
to b
.
It will be simpler if you use destructuring, there is no need for any crazy temp
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 array 2
is assigned to a
, and 1 is assigned to b
.
Although this method also creates a temporary array, this method looks at least more concise. Using destructuring, we can also exchange more than 2
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 the length
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 the colors
array to the firstColor
variable. If the array does not have any elements at index 0
, 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 index 1
in the colors
array Make an assignment.
When I started using React
and Redux
, 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 array fooNumbers
, fooNumbers
containing numbers
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 the foo
attribute from the object big
:
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
and map
.
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 of movie
objects. It's great to get title
as a string when deconstructing movies
. 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 the Symbol.iterator
method, and the iterator iterates title
.
Follows the iterable protocolallows movies
objects to be decomposed into title
by reading the first movies
The title
: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 variable title
and set the attribute ## The value of #movie.title is assigned to it.
greet function:
function greet(obj, nameProp) { const { [nameProp]: name = 'Unknown' } = obj; return `Hello, ${name}!`; } greet({ name: 'Batman' }, 'name'); // => 'Hello, Batman!' greet({ }, 'name'); // => 'Hello, Unknown!'
greet()# with 2
arguments ## Functions: object and property names. Inside
, destructuring assignment const {[nameProp]:name ='Unknown'} = obj
Use the form of square brackets[nameProp ]
Read the dynamic attribute name, and the name
variable receives the dynamic attribute value. A better approach is to specify a default value of "
" if the property does not exist. <h2><span style="font-size: 18px;">6. Conclusion</span></h2>
<p> Destruction is very useful if you want to access object properties and array items. </p>
<p>In addition to basic usage, array destructor can also conveniently exchange variables, access array items, and perform some immutable operations. </p>
<p>JavaScript offers greater possibilities, as you can define custom destruction logic using iterators. </p>
<blockquote><p>Original address: https://dmitripavlutin.com/5-interesting-uses-javascript-destructuring/</p></blockquote>
<p>For more programming-related knowledge, please visit: <a href="https://www.php.cn/course.html" target="_blank" textvalue="编程学习">programminglearning</a>! ! </p>
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!