如何在JavaScript中使用解构分配

news/2024/7/6 0:59:01

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.

简而言之, 解构意味着将对象或数组的值解压缩为变量。 在本指南的最后,您将看到如何使用它以及可以代替它的内容。

解构数组 (Destructuring Arrays)

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

销毁对象 (Destructuring Objects)

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

使用它传递功能参数 (Using It To Pass Function Arguments)

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.

通过将函数参数作为对象传递,它们将自动解析为独立的参数。 现在,我们传递一个具有匹配键-值对的对象,该函数将正常运行。

结论 (Conclusion)

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


http://www.niftyadmin.cn/n/3649617.html

相关文章

Java基础---集合框架二(ArrayList 接口)

2015-4-16 一、List集合 1、List集合特有方法 特有方法: voidadd(int index, E element) : 在当前集合中指定位置 添加给定的元素 Objectget(int index) 返回集合中指定位置的元素。 intindexOf(Object o)返回此集合中第一次出现的指定元素的索引&…

Java基础---IO流三(字节流 字符流)

2015-04-23 一、转换流(IO流续) 1、编码表概述 由字符及其对应的数值组成的一张表 编码 把看得懂的变成看不懂的 解码 把看不懂的变成看得懂的 常见的编码表 ASCII:用7位来表示一个数据 ISO-8859-1:在西欧使用,…

Android项目实战系列—基于博学谷(七)课程模块(下)

由于这个模块内容较多,分为上、中、下 三篇博客分别来讲述,请耐心阅读。 课程模块分为四个部分 课程列表 课程详情 视频播放 播放记录 课程模块(下)主要讲述视频播放和播放记录两个部分 一、视频播放 1、视频播放界面 (1&#…

angular id标记_使用传单在Angular中构建地图,第2部分:标记服务

angular id标记In my last post, we set up our environment to create a basic map using Leaflet and Angular. Let’s go a bit further now and add markers to our map. 在上一篇文章中 ,我们设置了环境以使用Leaflet和Angular创建基本地图。 现在让我们再走一…

Java高新技术---反射动态代理

2015-04-25 一、反射 1、概述 JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属 性;这种动态获取的信息以及动态调用对象的方…

[xmlpull]XmlPull常见错误

[xmlpull]XmlPull常见错误编写者日期关键词郑昀ultrapower2005-9-28Xmlpull kxml java Xmlpull官方站点:http://www.xmlpull.org/优点:不必等整个文档解析完成,部分求值结果早就可以开始反馈给用户。What Is It?XmlPull project is dedicate…

C#实战系列—学生信息管理系统(一)项目展示

最近在整理自己电脑上的学习资料,突然发现大二时小组一起做的C#项目——学生信息管理系统。就想运行起来玩玩。可是现在主机里面都是一些开发Android和Java的软件。visual studio 2010也早就卸载了。不过想到我们开发的这个系统在Windows 10系统上的兼容性不太好。所…

在VS Code中使用ESLint进行整理和格式化

介绍 (Introduction) When writing JavaScript with an editor such as Visual Studio Code, there are a number of ways you can ensure your code is syntactically correct and in line with current best practices. For example, it is possible to integrate a linter s…