当前位置: 首页 > 编程日记 > 正文

如何充分利用JavaScript(ES6)中的解构功能

by Joanna Gaudyn

乔安娜·高登(Joanna Gaudyn)

Destructuring was a new addition to ES6. It took inspiration from languages like Python and allows you to extract data from arrays and objects into distinct variables. It might sound like something you’ve done in the earlier versions of JavaScript already, right? Have a look at two examples.

销毁是ES6的新增功能。 它从Python之类的语言中汲取了灵感,并允许您从数组和对象中提取数据到不同的变量中。 听起来您已经在早期版本JavaScript中完成过操作,对吧? 看两个例子。

The first one extracts data from an object:

第一个从对象中提取数据:

const meal = {  name: 'pizza',  type: 'marinara',  price: 6.25};
const name = meal.name;const type = meal.type;const price = meal.price;
console.log(name, type, price);

Prints:

印刷品:

pizza marinara 6.25
比萨比萨饼6.25

And the second one from an array:

第二个来自数组:

const iceCreamFlavors = ['hazelnut', 'pistachio', 'tiramisu'];const flavor1 = iceCreamFlavors[0];const flavor2 = iceCreamFlavors[1];const flavor3 = iceCreamFlavors[2];console.log(flavor1, flavor2, flavor3);

Prints:

印刷品:

hazelnut pistachio tiramisu
榛子开心果提拉米苏

The thing is, though, that neither of these examples actually uses destructuring.

事实是,这些示例均未真正使用解构。

什么是解构? (What is destructuring?)

Destructuring lets you specify the elements you want to extract from an array or object on the left side of an assignment. This means much less code and exactly the same result as above, without losing readability. Even if it sounds odd at first.

通过解构,您可以指定要从分配左侧的数组或对象中提取的元素。 这意味着更少的代码和与上面完全相同的结果,而不会丢失可读性。 即使一开始听起来很奇怪。

Let’s redo our examples.

让我们重做我们的示例。

销毁对象 (Destructuring objects)

Here’s how we destructure values from an object:

这是我们如何从对象中解构值的方法:

const meal = {  name: 'pizza',  type: 'marinara',  price: 6.25};
const {name, type, price} = meal;
console.log(name, type, price);

Prints:

印刷品:

pizza marinara 6.25
比萨比萨饼6.25

The curly braces { } stand for the object which is being destructured and name, type, and price represent the variables to which you want to assign the values. We can skip the property from where to extract the values, as long as the names of our variables correspond with the names of the object’s properties.

大括号{ }代表正在被分解的对象, nametypeprice表示要为其分配值的变量。 只要变量的名称与对象的属性的名称相对应,就可以跳过从中提取值的属性。

Another great feature of object destructuring is that you can choose which values you want to save in variables:

对象解构的另一个重要功能是,您可以选择要保存在变量中的值:

const {type} = meal; will only select the type property from the meal object.

const {type} = meal; 只会从meal对象中选择type属性。

解构数组 (Destructuring arrays)

Here’s how our original example would be handled:

这是我们原始示例的处理方式:

const iceCreamFlavors = ['hazelnut', 'pistachio', 'tiramisu'];
const [flavor1, flavor2, flavor3] = iceCreamFlavors;
console.log(flavor1, flavor2, flavor3);

Prints:

印刷品:

hazelnut pistachio tiramisu
榛子开心果提拉米苏

The brackets [ ] stand for the array which is being destructured and flavor1, flavor2 and flavor3 represent the variables to which you want to assign the values. Using destructuring we can skip the indexes at which the values live in our array. Convenient, isn’t it?

方括号[ ]表示要进行解构的数组, flavor1flavor2flavor3表示要为其分配值的变量。 使用解构,我们可以跳过值存在于数组中的索引。 方便,不是吗?

Similarly as with an object, you can skip some values when destructuring an array:

与对象类似,在分解数组时可以跳过一些值:

const [flavor1, , flavor3] = iceCreamFlavors; will simply ignore flavor2.

const [flavor1, , flavor3] = iceCreamFlavors; 只会忽略flavor2

Long live laziness as a potent motivator for the invention of new shortcuts!

懒惰万岁是发明新捷径的有力动力!

Did you like this article? Maybe you’ll find these interesting too:

你喜欢这篇文章吗? 也许您也会发现这些有趣的东西:

What does yoga have to do with programming?You might be surprised.medium.freecodecamp.orgSpread operator and rest parameter in JavaScript (ES6)Both the spread operator and the rest parameter are written as three consecutive dots (…). Do they have anything else…medium.comAn overview of JavaScript iteratorsThe difference between for, for…in and for…of loopsmedium.freecodecamp.org

瑜伽与编程有什么关系? 您可能会感到惊讶。 medium.freecodecamp.org JavaScript(ES6)中 的扩展运算符和rest参数扩展运算符和rest参数都被写为三个连续的点(…)。 它们还有其他内容吗…… medium.com JavaScript迭代器概述 for,for…in和for…of循环之间的区别medium.freecodecamp.org

翻译自: https://www.freecodecamp.org/news/destructuring-in-javascript-es6-ee963292623a/

相关文章:

React 开发环境搭建

先来一个 React 官方文档的链接 点击跳转 搭建 React 的前期准备:你的本地环境需要安装 cnpm、node。 注:代码块中的 $ 代表: $后面是在命令行输入的命令,举例 $ npm start 解:实际上是应该打开命令行输入 npm st…

c++中的友元重载

1 语法 返回值类型 operator 运算符名称(形参列表) { 重载实体 } --------->operator和运算符名称在一起构造成新的函数名 2 案例 1 #include <iostream>2 3 using namespace std;4 5 class Complex6 {7 public:8 9 Complex(float x0,float y0) 10 :_…

WPF解析TTF 字体

偶遇需要自己解析 TTF 字体并显示&#xff0c;此做。。。 using System; using System.Collections.Generic; using System.Drawing.Text; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Windows; using System.W…

redux logic_Redux-Logic简介

redux logicby Sam Ollason通过萨姆奥拉森(Sam Ollason) Redux-Logic简介 (An Introduction to Redux-Logic) This article will go through a high-level overview of Redux-Logic. We will look at what is it, why it is needed, how it differs from other Redux middlewa…

[SDOI2009]HH的项链

题目背景 无 题目描述 HH 有一串由各种漂亮的贝壳组成的项链。HH 相信不同的贝壳会带来好运&#xff0c;所以每次散步完后&#xff0c;他都会随意取出一段贝壳&#xff0c;思考它们所表达的含义。HH 不断地收集新的贝壳&#xff0c;因此&#xff0c;他的项链变得越来越长。有一…

DvaJS 入门, 快速上手Dva

为什么要使用Dva? React 没有解决的问题 React 本身只是一个 DOM 的抽象层&#xff0c;使用组件构建虚拟 DOM。 如果开发大应用&#xff0c;还需要解决一个问题。 通信&#xff1a;组件之间如何通信&#xff1f;数据流&#xff1a;数据如何和视图串联起来&#xff1f;路由…

Static、DynamicResource学习笔记一

定义了资源后&#xff0c;我们可以在元素中直接使用该资源&#xff0c;但又分为StaticResource及DynamicResource两种方式。 StaticResource 静态资源在首次创建窗口时一次性的设置完毕&#xff0c;之后源资源对象本身发生的任何变化都会影响到使用该资源的元素&#xff0c;如果…

javascript迭代器_JavaScript迭代器概述

javascript迭代器by Joanna Gaudyn乔安娜高登(Joanna Gaudyn) JavaScript迭代器概述 (An overview of JavaScript iterators) for&#xff0c;for…in和for…of循环之间的区别 (The difference between for, for…in and for…of loops) Iteration might be one of the most c…

knockout学习笔记目录

关于knockout学习系列的文章已经写完&#xff0c;这里主要是做个总结&#xff0c;并且将目录罗列出来&#xff0c;方便查看。欢迎各位大神拍砖和讨论。 总结 kncokout是一个轻量级的UI类库&#xff0c;通过MVVM模式使前端的UI简单话&#xff0c;减少javascript代码的编写。通常…

ant Design Pro 登录状态管理

未登录自动跳转到登录页面&#xff0c;登录成功不跳转回登录页面的实现代码调用流程。 ant Design Pro 是一个企业中后台管理框架&#xff0c;开始做他&#xff0c;第一个肯定是要做登录&#xff0c;下面来看一下它是怎么登录的。 先看路由配置 Authorized.jsx代码&#xff1…

初级java开发学习路线_成为初级全栈Web开发人员的10分钟路线图

初级java开发学习路线So you have started your journey into the world of web development. But what do you learn first? The Internet is overloaded with a wealth of information about the millions of different technologies that a web developer can know.因此&am…

国外物联网平台初探(四):Ayla Networks

定位 Ayla企业软件解决方案为全球部署互联产品提供强大的工具 功能 Ayla的IoT平台包含3个主要组成部分&#xff1a; (1) Ayla嵌入式代理Ayla Embedded Agents (2) Ayla云服务Ayla Cloud Services (3) Ayla应用库Ayla Application Libraries 设备 开发者使用任何微控制器、操作系…

《英语语法新思维初级教程》学习笔记(一)名词短语

参考资料&#xff1a; 1. 《英语语法新思维初级教程》 ▶ 知识点 ▼ 英语是“固定词序语言&#xff08;a fixed-word-order language&#xff09;”。 ▼ 语言的构造级别分五个层次&#xff1a;1. 词&#xff08;word&#xff09;&#xff1b;2. 短语&#xff08;phase&#xf…

根据数组中对象的属性值排序倒叙

数组中对象的属性值排序倒叙demo function compare(e) {return function (a, b) {var value1 a[e];var value2 b[e];return parseInt(value1) - parseInt(value2);} } var arr[{a:2},{a:3},{a:1}];var arr2 arr.sort(compare(time)).reverse();console.log(arr2) //[{a:3}…

!! javascript_产量! 产量! 生成器如何在JavaScript中工作。

!! javascriptby Ashay Mandwarya ?️??由Ashay Mandwarya提供吗&#xff1f; 产量&#xff01; 产量&#xff01; 生成器如何在JavaScript中工作。 (Yield! Yield! How Generators work in JavaScript.) If the title doesn’t already give a hint, we will be discussin…

ACM 竞赛高校联盟 练习赛 第二场 BC

B. 题解&#xff1a; 枚举约数即可&#xff0c;判断n个数能否填约数的整数倍 #include <iostream> #include <cstring> #include <cstdio> using namespace std; typedef long long LL; int main(){LL T, n, m;cin>>T;while(T--){cin>>n>>…

在一个数组中查找两个重复出现的数字

题目如下&#xff1a;现有一个数组长度为n1&#xff0c;里面存放有1到n-2&#xff0c;顺序不定&#xff0c;其中有两个数字出现了两次&#xff0c;现在要找出那两个数字。 例子A{2, 3, 1, 4, 5, 2, 4}&#xff0c; 这个数组长度为7&#xff0c;存放了1到5&#xff0c;但2和4出现…

React 组件生命周期

组件的生命周期可分成三个状态&#xff1a; Mounting&#xff1a;已插入真实 DOMUpdating&#xff1a;正在被重新渲染Unmounting&#xff1a;已移出真实 DOM 生命周期的方法有&#xff1a; componentWillMount 在渲染前调用,在客户端也在服务端。 componentDidMount : 在第一…

银行软件开发实习生_如何找到学生的软件开发人员实习生

银行软件开发实习生by Grazietta Hof由Grazietta Hof 如何找到学生的软件开发人员实习生 (How to find a Software Developer Internship as a student) Side note: Although this article is directed at students (because I am one so I can easily relate), I’m sure a l…

MAC OS X El CAPITAN 搭建SPRING MVC (1)- 目录、包名、创建web.xml

一、 下载STS&#xff08;Spring Tool Suite&#xff09; 官方地址&#xff1a;http://spring.io/tools/sts 下载spring tool suite for mac 最新版本。这个IDE是很不错的&#xff0c;其中spring插件已经配置好了。下载解压缩&#xff08;一定要英文目录下&#xff09;&#xf…

iOS小知识点记录

1>UITextField实现leftView: self.inputTextField [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 200, 25)];self.inputTextField.delegate self;self.inputTextField.font [UIFont systemFontOfSize:15];self.inputTextField.placeholder " 想说点什么?…

Ant Design Pro 网络请求,视图绑定model并且渲染到页面 umi-request

封装网络请求,在service中新建接口,在model调用service,在视图绑定model并且得到网络请求的回调函数,获取网络请求的数据渲染到页面。 网络请求数据走向; 1.在utils/request.js 封装网络请求; /*** request 网络请求工具* 更详细的 api 文档: https://github.com/umijs…

2019机器学习比赛_2019顶尖的机器学习课程

2019机器学习比赛With strong roots in statistics, Machine Learning is becoming one of the most interesting and fast-paced computer science fields to work in. There’s an endless supply of industries and applications machine learning can be applied to to mak…

HTML5 canvas画图

HTML5 canvas画图 HTML5 <canvas> 标签用于绘制图像&#xff08;通过脚本&#xff0c;通常是 JavaScript&#xff09;。不过&#xff0c;<canvas> 元素本身并没有绘制能力&#xff08;它仅仅是图形的容器&#xff09; - 您必须使用脚本来完成实际的绘图任务。getCo…

排序算法7---快速排序算法

原理&#xff1a; 通过一趟排序将待排记录分割成独立的两部分&#xff0c;其中一部分记录的关键字均比另一部分记录的关键字小&#xff0c;则可分别对这两部分记录继续进行排序&#xff0c;以达到整个序列有序的目的。 #include <stdio.h> #define MAXSIZE 9typedef stru…

dispatch callback ant design pro 网络请求回调函数

index.jsx 代码解析:在组件初次渲染时调用 model 中 命名空间为 a_models 的 getData 网络请求,传了一个patload 参数和 callback 回调函数过去,然后通过 this.setState ()更新视图的 state。 import { Form, Tabs,Affix, Button,Input,Table } from antd; import Re…

bigquery使用教程_如何使用Python和Google BigQuery构建机器人以自动执行您的笨拙任务...

bigquery使用教程Do you have repetitive tasks? Something that you do regularly, every week or even every day? Reporting might be one of your weekly or daily tasks. You query or ask for the data, and do some visualizations, then give it to your boss. What …

5S后返回首页

1 <!DOCTYPE html>2 <html>3 <head>4 <title>5S后返回首页</title> 5 <meta http-equiv"Content-Type" content"text/html; charsetgkb"/> 6 </head>7 <body>8 <h2>操作成功</h2>…

TypeScript 1

TypeScript 的由来 TypeScript 是 JavaScript 的一个超集&#xff0c;支持 ECMAScript 6 标准。 TypeScript 由微软开发的自由和开源的编程语言。 TypeScript 设计目标是开发大型应用&#xff0c;它可以编译成纯 JavaScript&#xff0c;编译出来的 JavaScript 可以运行在任何…

大龄屌丝自学笔记--Java零基础到菜鸟--028

泛型&#xff0c;for循环增强应用&#xff0c;静态导入&#xff0c;可变参数&#xff0c;asList() 1、泛型 约束了数据类型&#xff0c;格式为 <数据类型>&#xff0c;如&#xff1a;ArrayList<int> aListnew ArrayList<int>(); 泛型通配符&#xff1a;<?…