javascript编写

by Ashay Mandwarya ?️??

由Ashay Mandwarya提供吗?

如何在JavaScript中使用解构来编写更简洁,功能更强大的代码 (How to use destructuring in JavaScript to write cleaner, more powerful code)

Sometimes you have to destroy to build something new.

有时您必须破坏才能构建新的东西。

-Mistborn: The Hero of Ages

-Mistborn:时代的英雄

ES6 introduced us to one of the most awaited JavaScript features: destructuring. As a concept, Destructuring is not new or groundbreaking and some languages already had Destructuring(??) long before. But it was a much needed and requested feature in JavaScript .

ES6向我们介绍了最期待JavaScript功能之一:分解。 从概念上讲,Destructuring并不是新事物,也不是开创性的,某些语言早已具有Destructuring(??)。 但这是JavaScript中非常需要和要求的功能。

Destructuring is the process of breaking a structure. In the context of programming, the structures are the data structures, and destructuring these data structures means unpacking individual values from the data structure. In JavaScript, destructuring can be applied to an Object or an Array.

破坏是破坏结构的过程。 在编程的上下文中,结构是数据结构,对这些数据结构进行解构意味着从数据结构中解包单个值。 在JavaScript中,可以将解构应用于对象或数组。

Destructuring makes, breaks whatever…. what use do we have for it??

破坏使一切破裂。 我们有什么用?

Before answering that question, let’s have a formal definition for Destructuring. MDN to the rescue!

在回答这个问题之前,让我们对解构进行正式定义。 MDN进行救援!

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. -MDN

解构赋值语法是一个JavaScript表达式,可以将数组中的值或对象中的属性解压缩为不同的变量。 -MDN

Let’s look at some examples to have a better understanding of the basics of destructuring.

让我们看一些示例,以更好地了解解构的基础。

数组 (Arrays)

Sample 1:

范例1:

When I saw this simple piece of code the first time, I was baffled. I did’t get what happened. If you are like I was, let me try and explain.

当我第一次看到这段简单的代码时,我感到困惑。 我不知道发生了什么事。 如果您像我一样,请让我尝试解释。

In line 1, we define 2 variables a and b . In the next line both the variables are inside an array in the left hand side which in turn is equated to an actual array in the ride hand side. In the subsequent lines we print the values of a & b and we get 7 and 8 respectively which were the elements in the RHS array. The magic happening in line 2 is called destructuring.

在第1行中,我们定义2个变量ab 。 在下一行中,这两个变量都位于左侧数组中,而该数组又等效于乘车侧面中的实际数组。 在随后的几行中,我们打印ab的值,分别得到7和8,它们是RHS数组中的元素。 第2行中发生的魔术称为解构。

The LHS destructures the RHS and the values gained from unpacking the elements are assigned to the variables in order.

LHS解构了RHS,将拆包元素后获得的值按顺序分配给变量。

But why is the LHS inside an array???

但是为什么LHS放在数组中呢???

The destructuring assignment uses similar syntax, on the LHS compared to the RHS to define what values to unpack from the sourced variable.

与RHS相比,LHS上的解构分配使用类似的语法来定义要从源变量解包的值。

Sample 2:

范例2:

Here we have introduced another variable leftout in the code now. We have 2 different types of uses of leftout in the code.

在这里,我们介绍了另一个变量leftout在现在的代码。 我们在代码中使用了2种不同类型的leftout

  • [a,b,leftout]-> This assigns the third element in the array to leftout as expected.

    [a,b,leftout]-& 此阵列中的第三个元素分配to left按预期进行。

  • [a,b,…leftout]-> This gives the first 2 values to a and b respectively and the rest of the array is assigned to the leftout variable.

    [a,b,…leftout]-& 这将分别给出前两个值t oaa n db,并将数组的其余部分分配给he lefto变量。

The solution lies in the operator. This operator collapses all remaining arguments (rest) into one array. In the latter point, the first 2 array elements are assigned to a & b respectively, and the rest of the arguments are collapsed into an array (restructuring maybe??) and assigned to the leftout variable. We can verify the same by looking at the output.

解决方案在于运算符。 此运算符将所有剩余的参数( rest )折叠到一个数组中。 在后一点中,前2个数组元素分别分配给ab ,其余参数折叠成一个数组(可能进行重组)并分配给leftout变量。 我们可以通过查看输出来验证相同的结果。

对象 (Objects)

Sample 1:

范例1:

Destructuring works the same for object and arrays alike. The object in the LHS has properties a & b which are assigned respectively to the properties a & b of the RHS object. We get 1 & 2 respectively by printing them.

销毁对象和数组的工作原理相同。 LHS中的对象的属性ab分别分配给RHS对象的属性ab 。 我们通过打印分别得到1和2。

One thing to notice (if you have) is that there is a slight change in syntax (now you have).

要注意的一件事( 如果有的话 )是语法( 现在有了 )稍有变化。

In Object destructuring, the whole LHS & RHS are wrapped inside ()

在对象分解中,整个LHS和RHS都包裹在( )

We can see the error we get when we do not wrap it inside (). It says declaration of statement expected.

如果不将其包装在().我们会看到错误(). 它说声明的声明是预期的。

What is actually happening is that enclosing something in curly brackets {} confuses JavaScript so that it considers it a block and not an Object. Due to that, it is looking for a declaration for the block (function declaration), so we enclose the code within (). This makes it an expression rather than a block, and we get our results.

实际发生的情况是,将某些内容括在大括号{}会使JavaScript感到困惑,因此它会将其视为一个块而不是一个对象。 因此,它正在寻找该块的声明( 函数声明 ),因此我们将代码包含在() 。 这使它成为一个表达式而不是一个块,我们得到了结果。

Sample 2:

范例2:

Again the rest operator. Works just like in arrays, except this time the rest values are collapsed inside an object because the structure to be used is defined by the LHS.

再一次是rest运算符。 就像在数组中一样工作,除了这次其余的值折叠在对象内部是因为要使用的结构是由LHS定义的。

重组的目的是什么? (What is destructuring used for?)

As seen from above examples, we now know the importance of destructuring. There are a lot of uses and different cases of how destructuring can be used for both Objects and Arrays. We will try some of them. (P.S. — the examples are valid for both objects and arrays unless otherwise mentioned.)

从上面的示例可以看出,我们现在知道了结构重组的重要性。 如何将解构用于对象和数组有很多用途和不同情况。 我们将尝试其中的一些。 ( PS — 除非另有说明,否则示例对对象和数组均有效。 )

变量分配 (Variable assignment)

We already saw how variables are assigned in the above examples, so let’s have a look at another one.

在上面的示例中,我们已经了解了变量的分配方式,因此让我们看一下另一个示例。

In this example an already created array is directly assigned for destructuring. Values are assigned to the variables nonetheless.

在此示例中,已经创建的数组直接分配给销毁。 尽管如此,仍将值分配给变量。

The same goes for the Object.

对象也是如此。

默认值 (Default values)

Sometimes it can happen that we define n number of variables to get values from destructuring, but the array/object might only have n-x elements. In this case x variables will be assigned undefined.

有时可能会发生这样的情况,我们定义n个变量以从解构中获取值,但是数组/对象可能只有nx元素。 在这种情况下, x变量将被分配为undefined

We can see that b is undefined because the array simply does not have that many elements to destructure and assign every variable.

我们可以看到b是未定义的,因为数组根本没有太多的元素可以解构和分配每个变量。

The solution to that is to give default values to the variables, so if there are not enough elements the variables take default values rather than go undefined.

解决方案是为变量提供默认值,因此,如果没有足够的元素,变量将采用默认值而不是未定义。

交换 (Swapping)

Swapping is the process of interchanging values between 2 or more variables. A standard way of performing swapping is either using a temporary variable or using XOR. In JavaScript the same can be done using destructuring.

交换是在两个或多个变量之间交换值的过程。 执行交换的标准方法是使用临时变量或XOR。 在JavaScript中,可以使用解构来完成此操作。

Swap using a variable temp. The code is self explanatory.

使用可变温度交换。 该代码不言自明。

Using destructuring we just swap the position of elements and Voilà! Swap done.

使用解构,我们只是交换元素和Voilà的位置! 交换完成。

忽略价值 (Ignoring values)

We can capture and use only the values which are required and reject or ignore the unnecessary values.

我们只能捕获和使用必需的值,而拒绝或忽略不必要的值。

Here we can see that we ignored the middle value by not assigning it to any variable thus saving us the hassle.

在这里我们可以看到,通过不将中间值分配给任何变量,我们忽略了中间值,从而避免了麻烦。

间接分配函数返回 (Indirect assignment of a function return)

Here we can see that the function x returns an array. On line 4 where we destructure, we provide the function call which returns the array and not the array directly. It makes the code tidy and easy to read and understand.

在这里我们可以看到函数x返回一个数组。 在第4行进行结构分解的地方,我们提供了函数调用,该函数调用返回数组而不是直接返回数组。 它使代码整洁,易于阅读和理解。

分配给新变量 (Assignment to new variables)

Properties can be unpacked from an object and assigned to a variable with a different name than the object property.<Applicable to objects only>

可以从对象中解压缩属性,并将其分配给名称与对象属性不同的变量。<仅适用于对象>

We can see that the values for properties are also variables to whom values are assigned via destructuring.

我们可以看到,属性值也是通过解构分配值的变量。

嵌套对象和数组解构 (Nested object and array destructuring)

As we can see, that data is an object which has a property called location which in turn contains an array whose elements are objects.

如我们所见,数据是一个对象,它具有一个称为location的属性,该属性又包含一个数组,其元素为对象。

With destructuring we have to get the values of all the properties present inside the object inside the location array.

通过解构,我们必须获取位置数组内对象内部存在的所有属性的值。

So we created an object called obj which contains the same structure as the data object, and the values we want to unpack are provided as variables (mylatitude,mylongitude,mycity). These in turn are equated to the data array (same as the destructuring syntax before). When the variables are printed we get the respective values.

因此,我们创建了一个名为obj的对象,该对象包含与数据对象相同的结构,并且我们要解压缩的值以变量(mylatitude,mylongitude,mycity)的形式提供。 这些依次等同于数据数组(与之前的解构语法相同)。 当变量被打印时,我们得到各自的值。

使用for-of循环进行销毁 (Destructuring with for-of loop)

In the above code snippet, we have a people array of objects whose properties in turn contain an object (people > object >family). Now we want to unpack some of the values from the object using for..of loop.

在上面的代码片段中,我们有一个对象的people数组,其属性又包含一个对象(people> object> family)。 现在,我们要使用for..of循环从对象中解压缩一些值。

In the loop we have assigned an object variable, with the same structure as in the people array, ignoring the values we don’t need. We have assigned variables n & m respectively to the name and mother properties, because these are the values we want to unpack. Inside the loop we print the variables and we get the needed values.

在循环中,我们分配了一个对象变量,该变量具有与people数组相同的结构,而忽略了我们不需要的值。 我们已分别将变量n和m分配给名称和母属性,因为这些是我们要解压的值。 在循环内部,我们打印变量并获得所需的值。

大图景。 (The Big picture.)

You have to use destructuring in your code or practice it to actually get a hang of it. It seems simple in the examples because the examples are just to make you understand the basics. With complex/multiple operations (reduce()!), desctructuring might get confusing quickly, which we don’t want!

您必须在代码中使用解构或进行实践才能真正掌握它。 在这些示例中看起来很简单,因为这些示例只是为了使您理解基础。 使用复杂/多个操作(reduce()!),解构可能很快变得令人困惑,这是我们不希望的!

Moreover you might also think destructuring is just sugar syntax for performing a set of tasks (like we can give variables the value of each element from an array using a for loop). To an extent we can say it is sugar, but when we look at the broader image ‘The Big Picture’ we will get why destructuring has more value than just a code minimizer.

此外,您可能还认为解构只是执行一组任务的糖语法(例如,我们可以使用for循环为变量赋予数组中每个元素的值)。 在某种程度上,我们可以说这是糖,但是当我们看宽泛的“大图景”时,我们将明白为什么解构不仅具有代码最小化器的价值,还具有更多的价值。

JavaScript has many operations for both extracting as well as constructing data, but all of them work on one element at a time.

JavaScript具有许多用于提取和构造数据的操作,但是所有这些操作一次只能处理一个元素。

For constructing

用于构造

For extracting (still one at a time)

用于提取 (一次仍然提取 )

Although there is a syntax for constructing multiple properties at a time, but it can only be used at the time of assignment — it cannot be used for altering an existing object.

尽管有一种语法可以一次构造多个属性,但是只能在分配时使用-不能用于更改现有对象。

Before ES6 was introduced, there was no mechanism for extracting all data at once. That’s where destructuring has really come to shine. It lets you extract multiple properties from an object. We have seen this in the above examples.

在引入ES6之前,没有一种可以一次提取所有数据的机制。 那是真正意义上的解构的地方。 它使您可以从一个对象中提取多个属性。 在上面的示例中我们已经看到了这一点。

陷阱 (Pitfalls)

There is only one I can think of and we discussed it:

我只能想到一个,我们进行了讨论:

  • A statement should not start with a curly bracket {

    声明不应以大括号{

结论 (Conclusion)

I tried to simplify destructuring by demonstrating as many destructuring use cases as possible. I hope it made this concept clear to you. Now you can use destructuring to write powerful and clean code.

我试图通过演示尽可能多的销毁用例来简化销毁。 我希望它可以使您清楚这个概念。 现在,您可以使用解构来编写功能强大且简洁的代码。

翻译自: https://www.freecodecamp.org/news/how-to-use-destructuring-in-javascript-to-write-cleaner-more-powerful-code-9d1b38794050/

javascript编写

javascript编写_如何在JavaScript中使用解构来编写更简洁,功能更强大的代码相关推荐

  1. javascript案例_如何在JavaScript中使用增强现实-一个案例研究

    javascript案例 by Apurav Chauhan 通过Apurav Chauhan 如何在JavaScript中使用增强现实-一个案例研究 (How to use Augmented Re ...

  2. javascript国际化_如何在JavaScript中实现国际化(i18n)

    javascript国际化 朱利安· 莫茨 ( Julian Motz) , 帕纳约提斯· 维利萨拉科斯 ( Panayiotis Velisarakos) , 菲尔丹 ·史蒂芬 ( Vildan S ...

  3. javascript写入_如何在JavaScript中写入HTML元素?

    javascript写入 写入HTML元素 (Writing into an HTML element) To write string/text into an HTML element, we u ...

  4. windows驱动程序编写_如何在Windows中回滚驱动程序

    windows驱动程序编写 Updating a driver on your PC doesn't always work out well. Sometimes, they introduce b ...

  5. bash 脚本编写_如何在Bash中编写循环

    bash 脚本编写 人们想要学习Unix shell的一个常见原因是释放批处理的功能. 如果要对多个文件执行某些操作,一种方法是构造一个遍历这些文件的命令. 在编程术语中,这称为执行控制,最常见的示例 ...

  6. jeesite如何已生成数据的数据源_如何在postman中自动生成接口请求数据,这个功能你需要知道,可结合浏览器和两大抓包工具使用...

    在做接口调试或测试时,请求中的每个参数都要按照接口文档填写到postman的对应位置中,很是麻烦.那是否有这样一个功能?可以帮我们自动生成接口数据,无需修改,直接发送请求就可以呢. 这里面我们需要借助 ...

  7. vue路由跳转权限_如何在vue中实现路由跳转判断用户权限功能?

    实现这类校验有几个步骤. 1.设置路由是否需要校验的阀值. // 路由配置的地方谁知阀值 routes:[ { name:'admin', path:'/admin', component:'..., ...

  8. 如何在 JavaScript 中使用对象解构

    对象解构是一个有用的 JavaScript 功能,用于从对象中提取属性并将其绑定到变量. 更好的是,对象解构可以在一个语句中提取多个属性,可以从嵌套对象访问属性,并且可以在属性不存在时设置默认值. 在 ...

  9. javascript排序_鸡尾酒在JavaScript中排序

    javascript排序 Just want the code? Scroll all the way down for two versions of the code: 只需要代码? 一直向下滚动 ...

最新文章

  1. iOS视频流采集概述(AVCaptureSession)
  2. 关于Opengl中将24位BMP图片加入�一个alpha通道并实现透明的问题
  3. Fedora开启FTP服务
  4. 用numpy autograd 实现牛顿迭代
  5. 动态规划 - 装配线调度问题
  6. VTK:Filtering之ExtractVisibleCells
  7. serv-u 自定义html,Serv-U FTP鲜为人知的技巧(自定义欢迎界面)
  8. python-pygame声音模块的使用
  9. NFS双机热备探究实验
  10. VHDL半整数与奇数分频器设计实验
  11. 信息化案例:国家电投
  12. 华为机试高频题目(Java实现)
  13. threejs开启对数深度缓存区时、着色器深度混乱
  14. 富文本框wangEditor
  15. 重庆邮电大学计算机学院蓝桥杯,第七届蓝桥杯大赛个人赛(软件类)-重庆赛区获奖名单...
  16. ROS 问题(topic types do not match、topic datatype/md5sum not match、msg xxx have changed. rerun cmake)
  17. 软件项目管理-——project 2019 专业版
  18. Docker进入容器报错
  19. matlab使用杂谈5-fftshift函数的使用
  20. Unity2020找不到Device Simulator

热门文章

  1. xlrd读取单元格演练
  2. javascript 西瓜一期 01.什么是编程 什么是编程语言
  3. linux-mysql了解
  4. django-中间件,视图函数调用前会执行的
  5. python-双层嵌套循环-打印小星星
  6. Java-使用反射获取类型信息
  7. Effective_STL 学习笔记(四) 用 empty 来代替检查 size() 是否为0
  8. Algs4-1.3.33矩阵库
  9. ecshop程序结构说明
  10. mysql增量备份及恢复解决方案