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

青灯夜游
Release: 2022-10-24 21:18:00
forward
1224 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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template