


Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays
This article brings you relevant knowledge about javascript, which mainly organizes issues related to destructuring and assigning objects and arrays, including array destructuring, object destructuring, function parameter parsing, etc. Let’s take a look at the content below. I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end】
Object (Object
) and array (Array
) are the two most commonly used data structures in JavaScript
. The common feature of both is that they can store a large amount of data.
The problem is that when we pass parameters and calculate them, we may only need part of the object and array, not the entire object/array.
At this time, you need to use Destructuring assignment to unpack the object/array and obtain part of its internal data. The following uses cases to introduce the application of destructuring assignment in programming.
Array destructuring
The so-called array destructuring is to obtain part of the data that is useful to us in the array. For example:
let arr = ['first','second']let [x, y] = arr //解构操作console.log(x,y)
The code execution result is as follows:
The content of the code is very simple. It assigns the contents of the array to two variables and then outputs them.
Array destructuring can also be used in conjunction with the split
function, which is elegant and high-end:
let [x, y] = 'hello world'.split(' ')console.log(x, y)
The code execution results are as follows:
Destructuring does not change the original array
Destructuring can also be called "destructuring assignment". Its essence is to copy the elements of the array to variables, so the original array does not change in any way.
let [x, y] = arr //{1}let x = arr[0] //{2}let y = arr[1]
{1}
and {2}
in the above code are completely equivalent, but the destructuring and assignment method is more concise.
Ignore array elements
If we use destructuring assignment, we hope to get the 1
, 3
th element of the array, but not the first 2
elements, what should we do?
For example:
let [x, ,z] = ['first','second','third']console.log(x,z)
The code execution result is as follows:
In this way, commas are used to avoid the second element.
Iterable objects use destructuring
Destructuring assignment is not necessarily used on arrays, it can be used on any iterable object, for example:
let [x, y, z] = 'xyz'let [a, b, c] = new Set(['a','b','c'])console.log(x,y,z)console.log(a,b,c)
Code Execution result:
#Destructuring assignment will iterate the value on the right and then assign the value to the variable on the left.
Assign a value to any variable
The right side of the =
of the destructuring assignment can be any and iterated object, while the left side can be any variable that can be assigned a value, and Not limited to simple variables.
Give a chestnut:
let country = {};[country.name, country.desc] = 'China Beautiful'.split(' ')console.log(country.name,country.desc)
Code execution result:
Note: The points in the first line of code The number must be added, otherwise you will encounter an error! For details, you can learn about "JavaScript Syntax Structure".
Combined with the .entries() method
Object.entries(obj)
method will return the attribute list of the object obj
, we can also Destructuring syntax is used here:
let country = { name:'China', desc:'a beautiful country'}for(let[k, v] of Object.entries(country)){ console.log(k,v)}
Code execution result:
Combined with Map
Due to the Map
object It is iterable itself, so you can directly use the for...of
syntax combined with the destructuring syntax:
let map = new Map()map.set('name','China')map.set('desc','Beautiful Country')for(let [k, v] of map){ console.log(k,v)}
Code execution result:
Variable exchange
There is a famous technique for destructuring assignment, exchanging the values of two variables:
let a = 1;let b = 2;[a,b]=[b,a]console.log(`a=${a},b=${b}`)
Code execution result:
Extra elements
During the process of performing destructuring assignment, there are two situations:
- There are more elements on the left than on the right, and the value on the left uses
undefined
Fill; - The elements on the right are more than the elements on the left. Ignore the excess. You can also use
...
to collect;
There are more elements on the left than on the right :
let [a,b,c] = 'ab'console.log(a,b,c)
Code execution result:
可见最后一个变量c
被赋值undefined
。
我们也可以为多余的左侧变量赋予默认值,举个例子:
let[a=0,b=0,c=0] = 'ab'console.log(c)
代码执行结果如下:
右侧多于左侧:
let [a, b] = 'abcd'console.log(a,b)
代码执行结果如下:
这里就没什么可解释的了。
但是,如果我们希望获得其他元素应该怎么做呢?
举例如下:
let [a, b, ...others] = 'abcdefg'console.log(others)
代码执行结果:
这里的变量others
就将所有剩余选项全部都收集了起来,others
可以是任何合法的变量名,不局限于others
本身。
对象解构
解构语法同样使用于对象,只不过语法上稍有不同:
let {var1, var2} = {...}
举个例子:
let country = { name:'China', desc:'Beautiful'};let {name,desc} = country;console.log(name,desc)
代码执行结果:
**注意:**这里的变量顺序是没有影响的,我们也可以交换name
和desc
的位置,如:
let {desc,name}=country;
代码的执行结果并没有什么变化。
属性变量映射
当然我们也可以指定变量和属性的映射,例如:
let country = { name:'China', desc:'Beautiful'}//对应的规则:{对象属性:目标变量}let {name:desc,desc:name} = country;console.log(`name:${name},desc:${desc}`)
代码执行结果:
这样我们就强行交换了变量和属性之间的映射方式,或许下面的例子更直观:
let obj = { x:'xiaoming', y:'18'}let {x:name,y:age}=obj;console.log(`name:${name},age:${age}`)
代码执行结果:
默认值
和数组一样,我们也可以使用=
为变量指定默认值。
举例如下:
let obj = { name:'xiaoming', age:18}let {name='xiaohong',age=19,height=180} = obj console.log(height)
代码执行结果:
这样,即使对象没有对应的属性,我们同样可以使用默认值代替。
我们还可以结合映射和默认值:
let obj = { x:'xiaoming', y:'18'}let {x:name='xxx',y:age=18,height:height=180}=obj;console.log(`name:${name},age:${age},height:${height}`)
代码执行结果:
多余的属性
和数组一样,我们可以取对象的一部分属性:
let obj = { x:'x', y:'y', z:'z'}let {x:name}=obj console.log(name)
我们还可以使用...
将剩余的属性重新打包为一个新对象:
let obj = { x:'x', y:'y', z:'z'}let {x,...others}=obj console.log(others)
代码执行结果:
let陷阱
可能有写童鞋已经发现了,我们在使用解构操作时,总是把一个对象赋值给一个使用let
新定义的变量,例如:let {...} = obj
。
如果我们使用已经存在的对象,会发生什么事呢?
let a,b,c;//定义三个变量{a,b,c} = {a:'a',b:'b',c:'c'}console.log(a,b,c)
代码执行结果如下:
为什么会出现这种错误呢?
这是因为JavaScript
会把主代码流中的{...}
作为一个代码块,代码块是一个独立的代码空间,用于语句的分组。
案例如下:
{ let a = 1; let b = 2; ...}
上例中的{a,b,c}
就被错误的当成了这样的代码块,为了告诉引擎这不是一个代码块,我们可以这样:
let a,b,c;//定义三个变量({a,b,c} = {a:'a',b:'b',c:'c'})//加括号console.log(a,b,c)
代码执行结果如下:
多层解析
如果对象出现了嵌套,相应的我们也可以使用对应的嵌套层次进行解析:
let People = { head:{ leftEye:'le', rightEye:'re' }, hands:['left-hand','right-hand'], others:'others'}let { head:{ leftEye, rightEye }, hands:[left_hand,right_hand], others} = People;console.log(leftEye,right_hand)
代码执行结果:
函数参数解析
有些情况下,一个函数需要非常多的参数,这不仅会让程序猿记忆困难,同时也会让代码变的冗长。
例如:
function createWin(title="Untitled",width=100,height=200,items=[]){ ...}
这种情况下,调用函数会变的非常困难。更令人苦恼的是,通常这些参数只要保持默认就可以了,而我们还要费尽心机的重写它们。就像这样:
createWin(title="Untitled",width=100,height=200,items=['i','j','k'])
解构赋值可以帮助我们解决这些问题,我们可以把对象传递给函数,而函数会自动的把对象解析为参数:
let options = { title:'NewWin', width:200, height:100, items:['items1','items2']}//传入的对象会被解构成下面的参数样式//等价于{title="Untitled",width=100,height=200,items=[]} = optionsfunction createWin({title="Untitled",width=100,height=200,items=[]}){ console.log(`title:${title},width:${width},height:${height},items:[${items}]`)}createWin(options)//只需要传递一个对象
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of Detailed explanation of the basics of destructuring assignment of JavaScript objects and arrays. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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 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

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

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.

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

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

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).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
