Table of Contents
1. Swap variables
2. Access array item
3. Immutable operations
4. Destructuring iterables
5. Destructuring dynamic properties
6. 总结
Home Web Front-end JS Tutorial Let's talk about 5 interesting ways to use JS deconstruction

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

Oct 24, 2022 pm 09:18 PM
javascript

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

temp is a temporary variable, which saves the value of a, and then assigns the value of b to a, and finally assign the value of a saved in temp to b, completing the exchange.
Destructuring assignment Makes 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 to a, the second item (i.e. value 1) is assigned to b, 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 the colors array to the firstColor variable. 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 comma to the left of destructuring: it means to ignore the first element an element. secondColor is assigned by the element at index 1 in the colors array.

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 array fooNumbers, which contains all elements except the first element in the numbers array. 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 object small, which contains bigAll properties in the object except the foo property.

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.
movies Contains a list of movie objects. When deconstructing movies, 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); // => &#39;Heat&#39;
Copy after login

movies The object implements the iterable protocol by defining Symbol.iterator. Iterator method: Iterate over the titles of movies.
Following the iteration protocol allows the movies object 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: &#39;Heat&#39; };

const { title } = movie;

title; // => &#39;Heat&#39;
Copy after login

const {title} = movieCreate a variable title and set the attribute movie.title value 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 = &#39;Unknown&#39; } = obj;
 return `Hello, ${name}!`;
}

greet({ name: &#39;Batman&#39; }, &#39;name&#39;); // => &#39;Hello, Batman!&#39;
greet({ }, &#39;name&#39;); // => &#39;Hello, Unknown!&#39;
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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles