This article will talk to you about 5 interesting uses of JavaScript destructuring (Destructuring). I hope it will be helpful to you!
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
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
[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
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'
Using array destructuring to achieve the same effect requires less code:
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.
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'
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]
[, ...fooNumbers] = numbers
Destructuring creates a new array fooNumbers
, which contains all elements except the first element in the numbers
array. numbers
The 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' }
Destructuring assignment combined with the object rest operator creates a new object small
, which contains big
All 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'
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); // => 'Heat'
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: 'Heat' }; const { title } = movie; title; // => 'Heat'
const {title} = movie
Create 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 = 'Unknown' } = obj; return `Hello, ${name}!`; } greet({ name: 'Batman' }, 'name'); // => 'Hello, Batman!' greet({ }, 'name'); // => 'Hello, Unknown!'
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!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools