JavaScript provides you with the ability to destructure objects and assign the individual units in one take. This allows you to get to the point of what you want to do and keep things clean.
JavaScript使您能够分解对象并一次性完成分配各个单元的功能。 这使您可以直截了当地,并保持工作整洁。
In brief, destructuring means to unpack the values of objects or arrays into variables. At the end of this guide, you will see how to use it and what it can replace for you.
简而言之, 解构意味着将对象或数组的值解压缩为变量。 在本指南的最后,您将看到如何使用它以及可以代替它的内容。
Prior to the development of destructuring assignments, if you had an array and wanted to assign some of it’s values to variables, you would do something like this:
在开发解构分配之前,如果您有一个数组并想将其某些值分配给变量,则可以执行以下操作:
let johnDoe = ["John", "Doe", "Iskolo"]
let firstName = johnDoe[0]
let lastName = johnDoe[1]
let title = johnDoe[2]
console.log(firstName, lastName, title) // John Doe Iskolo
You can get the same result by destructuring the array, like this:
您可以通过破坏数组来获得相同的结果,如下所示:
let johnDoe = ["John", "Doe", "Iskolo"]
let [firstName, lastName, title] = johnDoe
console.log(firstName, lastName, title) // John Doe Iskolo
This method allows you to pick any number of elements you want:
此方法使您可以选择任意数量的元素:
let johnDoe = ["John", "Doe", "Iskolo"]
let [firstName, lastName] = johnDoe
console.log(firstName, lastName) // John Doe
Or:
要么:
let johnDoe = ["John", "Doe", "Iskolo"]
let [, lastName, title] = johnDoe
console.log(lastName, title) // Doe Iskolo
You can do this with strings as well:
您也可以使用字符串进行此操作:
let [firstName, ,title] = "John Doe Iskolo".split(" ")
console.log(firstName, title) // John Iskolo
We can throw in the rest operator (...
) to collect the rest of the arguments:
我们可以使用rest运算符( ...
)来收集其余的参数:
let [firstName, ...others] = "John Doe Iskolo".split(" ")
console.log(firstName, others) // John Iskolo
And we can even bring in objects here:
我们甚至可以在这里引入对象:
let johnDone = {}
[johnDoe.first, johnDoe.last] = "John Doe Iskolo".split(" ")
console.log(johnDoe.first, johnDoe.last) // John Doe
In Looping Through Objects
在循环对象中
We can use destructuring assignment to loop through a key-value pair variable like an object or map:
我们可以使用解构赋值来遍历像对象或映射这样的键值对变量:
let obj = {
firstName : "John",
lastName : "Doe",
title : "Iskolo"
}
Object.keys(obj).forEach(key => {
console.log(`${key} : ${obj[key]}`)
})
We can spin that differently like this:
我们可以这样旋转:
let obj = {
firstName : "John",
lastName : "Doe",
title : "Iskolo"
}
for(let [key, value] of Object.entries(obj)) {
console.log(`${key} : ${value}`)
}
It might look like the same thing to you, but it is not. In using forEach
above, we pull the keys of the object into an array, then looping through that array of keys now and using those keys to pick out the values of objects.
在您看来,这似乎是同一回事,但事实并非如此。 在上面的forEach
,我们将对象的键拉到一个数组中,然后循环遍历该键的数组并使用这些键来选择对象的值。
In the second part, we just go straight and loop through each object entries and extracting the keys and values.
在第二部分中,我们直接遍历每个对象条目,并提取键和值。
Assigning default values We can assign defaults values, just for a situation where the variable we wish to destructure is empty:
分配默认值我们可以分配默认值,仅用于我们要分解的变量为空的情况:
let [firstName = "John", ,title = "Fire"] = "John Doe".split(" ")
console.log(firstName, title) // John Fire
Like we did with arrays, we can destructure objects as well. If you have ever used React, you may have seen this used when importing a module.
就像我们对数组所做的一样,我们也可以分解对象。 如果您曾经使用过React,那么您可能在导入模块时就已经看到了这个用法。
let obj = {
firstName : "John",
lastName : "Doe",
title : "Iskolo"
}
let {firstName, lastName) = obj
console.log(firstName, lastName) // John Doe
When destructuring objects, we use the keys
as variable names. This is how JavaScript knows which property of the object you want to assign. Unlike arrays where you use their index/positions in the assignment, here you use the keys.
解构对象时,我们将keys
用作变量名。 这就是JavaScript知道要分配对象的哪个属性的方式。 与在分配中使用其索引/位置的数组不同,此处使用键。
This destructuring works on any kind of object. If your object has nested values, you can still destructure that and extract the values into variables.
这种解构适用于任何类型的对象。 如果对象具有嵌套值,则仍可以对其进行解构并将值提取到变量中。
let obj = {
name : "John Doe",
address : {
city : "Omsk",
country : "Russia"
}
}
let {city, country} = obj.address
console.log(city, country) // Omsk Russia
You may have seen functions that look like this:
您可能已经看到如下函数:
function sumFunc(a = true, b = "", c = "", d = 0, e = false) {
console.log(a,b,c,d,e)
}
// Call the function
sumFunc(true, "", "", "", true)
// Or if we want to preserve default values
sumFunc(true, undefined, undefined, undefined, true)
This doesn’t look so good. It gets worse if you are trying to perform a function like making a chart and you need a lot of arguments to create the chat.
看起来不太好。 如果您尝试执行诸如绘制图表之类的功能,并且需要大量参数来创建聊天,则情况会变得更糟。
In a situation like this, destructuring can be useful:
在这种情况下,销毁可能会很有用:
function sumFunc({a = true, b = "", c = "", d = 0, e = false}) {
console.log(a,b,c,d,e)
}
let args = {a : false, e: true}
// Call the function
sumFunc(args)
By passing the function arguments as an object, they will get automatically resolved into independent arguments. Now, we pass an object with matching key-value pairs and the function will work nicely.
通过将函数参数作为对象传递,它们将自动解析为独立的参数。 现在,我们传递一个具有匹配键-值对的对象,该函数将正常运行。
Destructuring is an operation you can do without, however, you can already see how it makes you a better developer. Cleaner code, fewer repetitions and more structure over what you have.
销毁是您可以做的一项操作,但是,您已经知道它如何使您成为更好的开发人员。 干净的代码,更少的重复和更多的结构。
Use destructuring today and improve your code.
立即使用解构并改进代码。
翻译自: https://www.digitalocean.com/community/tutorials/how-to-use-destructuring-assignment-in-javascript