JavaScript(ES6)传播算子和rest参数简介

by Joanna Gaudyn

乔安娜·高登(Joanna Gaudyn)

JavaScript(ES6)传播算子和rest参数简介 (An intro to the spread operator and rest parameter in JavaScript (ES6))

扩展运算符和rest参数都被写为三个连续的点(…)。 他们还有其他共同点吗? (Both the spread operator and the rest parameter are written as three consecutive dots (…). Do they have anything else in common?)

点差运算符(…) (The spread operator (…))

The spread operator was introduced in ES6. It provides you with the ability to expand iterable objects into multiple elements. What does it really mean? Let’s check some examples.

点差运算符 在ES6中引入。 它使您能够将可迭代对象扩展为多个元素。 到底是什么意思 让我们来看一些例子。

const movies = ["Leon", "Love Actually", "Lord of the Rings"];console.log(...movies);

Prints:

印刷品:

Leon Love Actually Lord of the Rings
莱昂·洛夫实际上是指环王
const numbers = new Set([1, 4, 5, 7]);console.log(...numbers);

Prints:

印刷品:

1 4 5 7
1 4 5 7

You might notice that both the array from the first example and the set from the second one have been expanded into their individual elements (strings and digits respectively). How can this be of any use, you may ask.

您可能会注意到,第一个示例中的数组和第二个示例中的数组都已扩展为它们各自的元素(分别为字符串和数字)。 您可能会问,这怎么用?

The most common use is probably combining arrays. If you ever had to do this in the times before the spread operator, you probably used the concat() method.

最常见的用途可能是组合数组。 如果您曾经在传播运算符之前的某个时间执行此操作,则可能使用了concat()方法。

const shapes = ["triangle", "square", "circle"];const objects = ["pencil", "notebook", "eraser"];const chaos = shapes.concat(objects);console.log(chaos);

Prints:

印刷品:

[“triangle”, “square”, “circle”, “pencil”, “notebook”, “eraser”]
[“三角形”,“正方形”,“圆形”,“铅笔”,“笔记本”,“橡皮擦”]

That’s not too bad, but what the spread operator offers is a shortcut, which makes your code look way more readable too:

这还不错,但是散布运算符提供的是一种快捷方式,这也使您的代码看起来也更具可读性:

const chaos = [...shapes, ...objects];console.log(chaos);

Prints:

印刷品:

[“triangle”, “square”, “circle”, “pencil”, “notebook”, “eraser”]
[“三角形”,“正方形”,“圆形”,“铅笔”,“笔记本”,“橡皮擦”]

Here’s what we’d get if we tried doing the same without the spread operator:

如果我们尝试在没有传播运算符的情况下执行相同操作,则会得到以下结果:

const chaos = [shapes, objects];console.log(chaos);

Prints:

印刷品:

[Array(3), Array(3)]
[Array(3),Array(3)]

What happened here? Instead of combining the arrays, we got a chaos array with the shapes array at index 0 and the objects array at index 1.

这里发生了什么? 我们没有合并数组,而是获得了一个chaos数组,其中shapes数组位于索引0, objects数组位于索引1。

其余参数(…) (The rest parameter (…))

You can think of the rest parameter as the opposite of the spread operator. Just as the spread operator allows you to expand an array into its individual elements, the rest parameter lets you bundle elements back into an array.

您可以将rest参数视为与散布运算符相反的参数。 正如散布运算符允许您将数组扩展为单个元素一样,rest参数可以让您将元素捆绑回到数组中。

将数组的值分配给变量 (Assigning values of an array to variables)

Let’s have a look at the following example:

让我们看下面的例子:

const movie = ["Life of Brian", 8.1, 1979, "Graham Chapman", "John Cleese", "Michael Palin"];const [title, rating, year, ...actors] = movie;console.log(title, rating, year, actors);

Prints:

印刷品:

“Life of Brian”, 8.1, 1979, [“Graham Chapman”, “John Cleese”, “Michael Palin”]
“布莱恩生活”,8.1,1979年,[“格雷厄姆·查普曼”,“约翰·克莱斯”,“迈克尔·帕林”]

The rest parameter let us take the values of the movie array and assign them to several individual variables using destructuring. This way title, rating, and year are assigned the first three values in the array, but where the real magic happens is actors. Thanks to the rest parameter, actors gets assigned the remaining values of the movie array, in form of an array.

rest参数让我们采用movie数组的值,并使用destructuring将它们分配给几个单独的变量。 这样,将titleratingyear分配给数组中的前三个值,但是真正发生魔术的地方是actors 。 多亏了rest参数, actors以数组的形式被分配了movie数组的剩余值。

可变函数 (Variadic functions)

Variadic functions are functions which take an indefinite number of arguments. One good example is the sum() function: we can’t know upfront how many arguments will be passed to it:

可变参数函数是带有不确定数量的参数的函数。 一个很好的例子是sum()函数:我们无法预先知道将有多少参数传递给它:

sum(1, 2);sum(494, 373, 29, 2, 50067);sum(-17, 8, 325900);

In earlier versions of JavaScript, this kind of function would be handled using the arguments object, which is an array-like object, available as a local variable inside every function. It contains all values of arguments passed to a function. Let’s see how the sum() function could be implemented:

在JavaScript的早期版本中,此类函数将使用arguments对象处理, arguments对象是一个类似于数组的对象,可以在每个函数内部作为局部变量使用。 它包含传递给函数的参数的所有值。 让我们看看如何实现sum()函数:

function sum() {  let total = 0;    for(const argument of arguments) {    total += argument;  }  return total;}

It does work, but it’s far from perfect:

它确实有效,但远非完美:

  • If you look at the definition for the sum() function, it doesn’t have any parameters. It can be quite misleading.

    如果查看sum()函数的定义,则其中没有任何参数。 这可能会产生误导。

  • It can be hard to understand if you’re not familiar with the arguments object (as in: where the heck are the arguments coming from?!)

    如果您不熟悉arguments对象,可能很难理解(例如: arguments从何而来?!)

Here’s how we’d write the same function with the rest parameter:

这是我们使用rest参数编写相同函数的方式:

function sum(...nums) {  let total = 0;    for(const num of nums) {    total += num;  }  return total;}

Note that the for...in loop has been replaced with the for...of loop as well. We made our code more readable and concise at once.

请注意, for...in循环也已被for...of 循环替换。 我们使代码一次更可读,更简洁。

Hallelujah ES6!

哈利路亚ES6!

Are you just starting your journey with programming? Here’s some articles that might interest you as well:

您刚刚开始编程之旅吗? 以下是一些您可能也会感兴趣的文章:

  • Is a coding bootcamp something for you?

    编码训练营适合您吗?

  • Is career change really possible?

    职业转变真的有可能吗?

  • Why Ruby is a great language to start programming with

    为什么Ruby是一门很好的编程语言

翻译自: https://www.freecodecamp.org/news/spread-operator-and-rest-parameter-in-javascript-es6-4416a9f47e5e/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392518.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python爬虫消费者与生产者_Condition版生产者与消费者模式

概述:在人工智能来临的今天,数据显得格外重要。在互联网的浩瀚大海洋中,隐藏着无穷的数据和信息。因此学习网络爬虫是在今天立足的一项必备技能。本路线专门针对想要从事Python网络爬虫的同学而准备的,并且是严格按照企业的标准定…

【Python包】安装teradatasql提示找不到pycryptodome模块错误(pycrypto,pycryptodome和crypto加密库)...

1.问题描述 安装teradatasql时,出现错误Could not find a version that satisfies the requirement pycryptodome,具体如下: 2.解决方法 查看Python第三方库目录$PYTHON_HOME/lib/python3.6/site-packages目录下没有pycryptodome目录&#xf…

leetcode 860. 柠檬水找零(贪心算法)

在柠檬水摊上,每一杯柠檬水的售价为 5 美元。 顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零&#xff0…

简述yolo1-yolo3_使用YOLO框架进行对象检测的综合指南-第二部分

简述yolo1-yolo3In the last part, we understood what YOLO is and how it works. In this section, let us understand how to apply it using pre-trained weights and obtaining the results. This article is greatly inspired by Andrew Ng’s Deep Learning Specializat…

ubuntu配置JDK环境

>>>cd /usr/lib >>>mkdir java >>>cd java ###这里的参数表示接收他们的协议 >>>wget --no-check-certificate --no-cookies --header "Cookie: oraclelicenseaccept-securebackup-cookie" http://download.oracle.com/otn-pub/…

java cxf 调用wcf接口_JAVA 调用 WCF 服务流程

1. 将 WCF 服务发布到 Windows 服务(或者 IIS)此步骤的目的是为 WCF 服务搭建服务器,从而使服务相关的 Web Services 可以被 JAVA 客户端程序调用,具体步骤参考如下:(1) 发布到 Windows 服务(2) 发布到 IIS注:如果是将 WCF 服务…

react第三方组件库_如何自定义您的第三方React组件

react第三方组件库by Jacob Goh雅各布高 如何自定义您的第三方React组件 (How to customize your third party React components) Component libraries make our lives easier.组件库使我们的生活更轻松。 But as developers, you might often find yourselves in situations…

gcp devops_将GCP AI平台笔记本用作可重现的数据科学环境

gcp devopsBy: Edward Krueger and Douglas Franklin.作者: 爱德华克鲁格 ( Edward Krueger)和道格拉斯富兰克林 ( Douglas Franklin) 。 In this article, we will cover how to set up a cloud computing instance to run Python with or without Jupyter Notebo…

迅为工业级iMX6Q开发板全新升级兼容PLUS版本|四核商业级|工业级|双核商业级...

软硬件全面升级 1. 新增Yocto项目的支持 增加opencv等软件功能 2. 新近推出i.MX6增强版本核心板(PLUS) -性能更强 四种核心板全兼容 四核商业级2G/16G;双核商业级1G/8G ;四核工业级1G/8G ;四核增强版(PLUS) 3. 豪华配…

flume 中的 hdfs sink round 和roll

http://blog.csdn.net/kntao/article/details/49278239 http://flume.apache.org/FlumeUserGuide.html#exec-source 默认的是是SequenceFile所以数据存在hdfs上通过命令查看的时候会是乱码,如果此时需要修改filetype和writeFormat来修改 hdfs.fileTypeSequenceFileFile format:…

leetcode 649. Dota2 参议院(贪心算法)

Dota2 的世界里有两个阵营:Radiant(天辉)和 Dire(夜魇) Dota2 参议院由来自两派的参议员组成。现在参议院希望对一个 Dota2 游戏里的改变作出决定。他们以一个基于轮为过程的投票进行。在每一轮中,每一位参议员都可以行使两项权利中的一项: …

电力现货市场现货需求_现货与情绪:现货铜市场中的自然语言处理与情绪评分

电力现货市场现货需求Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works with…

PHP学习系列(1)——字符串处理函数(2)

6、chunk_split() 函数把字符串分割为一连串更小的部分。本函数不改变原始字符串。 语法:chunk_split(string,length,end) 参数: string——必需。规定要分割的字符串。 length——可选。一个数字,定义字符串块的长度。 end——可选。字符串值…

java做主成分分析_主成分分析PCA

PCA(Principal Component Analysis),即主成分分析,一种常用于数据降维分析的方法。要理解PCA的原理,首先需要理解矩阵变换的意义。矩阵变换,有两种意义:1,在当前坐标系下的向量,经过矩阵M变换后…

个人学习进度(第十六周)

转载于:https://www.cnblogs.com/lhj1017/p/7011993.html

什么叫静态构建版本号码_为什么要使用GatsbyJS构建静态网站

什么叫静态构建版本号码by Ajay NS由Ajay NS 为什么要使用GatsbyJS构建静态网站 (Why you should use GatsbyJS to build static sites) Gatsby has been growing over time, and I’m glad to see it in use by a huge number of sites like marketing sites, blogs, and gen…

leetcode 217. 存在重复元素

给定一个整数数组,判断是否存在重复元素。 如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。 示例 1: 输入: [1,2,3,1] 输出: true 代码 class Solution {public boolean containsDuplica…

C#正则表达式提取HTML中IMG标签的URL地址 .

/// <summary> /// 取得HTML中所有图片的 URL。 /// </summary> /// <param name"sHtmlText">HTML代码</param> /// <returns>图片的URL列表</returns> public static string[] GetHtmlImageUrlList(string sHtmlText) { // 定…

java datarow 使用_DataRow中的链接(数据表)

我正在动态构建一个DataTable&#xff0c;我正在尝试在DataRow中添加一个“链接”&#xff0c;我将其添加到DataTable中 . DataTable在创建后绑定到GridView .像这样的东西&#xff1a;DataTable dataTable new DataTable();foreach (Item item in items){DataRow row dataTa…

mac、windows如何强制关闭tomcat进程

方式1.打开cmd&#xff0c;或mac的终端&#xff0c;输入&#xff1a;① ps aux | grep "tomcat"&#xff0c;找到响应的进程id&#xff1b;② kill -9 查询的id&#xff0c;来强制关闭进程方式2&#xff1a;window&#xff0c;打开tomcat文件夹 --> bin --> sh…