Let's talk about 5 interesting ways to use JS deconstruction

青灯夜游
Release: 2022-10-24 21:18:00
forward
1115 people have browsed it

This article will talk to you about 5 interesting uses of JavaScript destructuring (Destructuring). I hope it will be helpful to you!

Let's talk about 5 interesting ways to use JS deconstruction

1. Swap variables

The common practice of exchanging two variables requires an additional temporary variable , let’s look at a simple scenario:

let a = 1; let b = 2; let temp; temp = a; a = b; b = temp; a; // => 2 b; // => 1
Copy after login

tempis a temporary variable, which saves the value ofa, and then assigns the value ofbtoa, and finally assign the value ofasaved intemptob, completing the exchange.
Destructuring assignmentMakes variable exchange simpler, no need to explicitly create temporary variables:

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

[a, b] = [b, a]Yes A destructuring assignment. On the right,creates an array[b, a], that is, [2,1], and the first item of this array (that is, the value 2) is assigned toa, the second item (i.e. value 1) is assigned tob, completing the exchange.
Although this method still creates a temporary array, this way of exchanging variables looks more concise.
Not only that, this method can also exchange more than 2 variables, as follows:

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

You can exchange as many variables as you want! However, swapping two variables is the most common scenario.

2. Access array item

You have an array that may be empty. You want to access the 1st, 2nd, or nth element of the array, but get a default value if the element doesn't exist.
Typically you would use the length property of an array:

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

Using array destructuring to achieve the same effect requires less code:

const colors = []; const [firstColor = 'white'] = colors; firstColor; // => 'white'
Copy after login

const [firstColor = 'white'] = colorsDestructuring assigns the first element of thecolorsarray to thefirstColorvariable. If the array does not have any elements at index 0, the "white" default value is assigned.
More flexibility is provided here, if you only want to access the second element, this is also possible:

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

Note the commato the left of destructuring: it means to ignore the first element an element.secondColoris assigned by the element at index 1 in thecolorsarray.

3. Immutable operations

When I started using React and later Redux, I was forced to write some code that involved immutability (The meaning here is to keep the original object unchanged). Although it was a bit difficult at first, I later saw its benefits:It was easier to handle one-way data flow.
Immutability means that it is forbidden to change the object. Fortunately, destructuring can help you easily implement certain operations in an immutable way.
Destructuring is combined with the rest operator (...) to remove the first element of the array:

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

[, ...fooNumbers] = numbersDestructuring creates a new arrayfooNumbers, which contains all elements except the first element in thenumbersarray.numbersThe array has not changed, maintaining the invariance of the operation.
In the same immutable way, you can remove properties from an object. Let's try to remove the foo attribute from the big object:

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

Destructuring assignment combined with the object rest operator creates a new objectsmall, which containsbigAll properties in the object except thefooproperty.

4. Destructuring iterables

In the previous section, destructuring was applied to the array. But you can destructure any object that implements the iterable protocol.
Many native primitive types and objects are iterable: arrays, strings, typed arrays, sets, and maps.
For example, you can deconstruct a string into several characters:

const str = 'cheese'; const [firstChar = ''] = str; firstChar; // => 'c'
Copy after login

You are not limited to native types. By implementing the iterable protocol, you can customize the deconstruction logic.
moviesContains a list ofmovieobjects. When deconstructingmovies, it would be great to get the movie title as a 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'
Copy after login

moviesThe object implements the iterable protocol by definingSymbol.iterator. Iterator method: Iterate over the titles of movies.
Following the iteration protocol allows themoviesobject to be deconstructed into titles. The specific method to obtain the title of the first movie is:const [firstMovieTitle] = movies.

5. Destructuring dynamic properties

In my experience, destructuring objects through properties is more common than array destructuring. The destructuring of the object seems simple:

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

const {title} = movieCreate a variabletitleand set the attributemovie.titlevalue is assigned to it.
When I first read about object destructuring, I was a little surprised that you don't have to know the property names statically, you can use dynamic property names to destructure objects!

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

greet()函数有两个参数:对象和属性名。在greet()函数内部,解构赋值const {[nameProp]: name = 'Unknown'} = obj使用中括号[nameProp]读取动态属性名,name变量作为别名接收动态属性值。如果属性不存在,你还可以给它赋一个默认值Unknown

6. 总结

如果你想访问对象属性和数组元素,那么解构非常有用。
在基本用法之上,数组解构便于交换变量、访问数组项、执行一些不可变的操作。
JavaScript提供了更大的可能性,因为你可以使用迭代器定义自定义的解构逻辑。

本文翻译自:5 Interesting Uses of JavaScript Destructuring

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

【相关推荐:javascript视频教程编程视频

The above is the detailed content of Let's talk about 5 interesting ways to use JS deconstruction. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!