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.pswp.cn/news/392518.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392518.shtml
英文地址,請注明出處:http://en.pswp.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…