了解ES6 The Dope Way第三部分:模板文字,擴展運算符和生成器!

by Mariya Diminsky

通過瑪麗亞·迪明斯基(Mariya Diminsky)

了解ES6 The Dope Way第三部分:模板文字,擴展運算符和生成器! (Learn ES6 The Dope Way Part III: Template Literals, Spread Operators, and Generators!)

Welcome to Part III of Learn ES6 The Dope Way, a series created to help you easily understand ES6 (ECMAScript 6)!

歡迎來到學習ES6的“攝影方式”的第三部分,該系列旨在幫助您輕松理解ES6(ECMAScript 6)!

Let’s adventure further into ES6 and cover three super valuable concepts:

讓我們進一步探索ES6,并介紹三個超有價值的概念:

  • Template Literals

    模板文字
  • Spread Operators

    點差運算符
  • Generators

    發電機

模板文字 (Template Literals)

Benefits:

好處:

  • Easy expression interpolation and method calls! See examples below.

    簡單的表達式插值和方法調用! 請參見下面的示例。
  • Including complex information in the format you want is simple!

    以所需的格式包含復雜的信息很簡單!
  • You don’t need to worry about multiple quotation marks, multi-lines, spaces, or using “+” sign either! Only two back ticks recognize all the information inside of them! Woohoo!

    您無需擔心多個引號,多行,空格或使用“ +”號! 只有兩個反勾號可以識別其中的所有信息! hoo!

Beware:

謹防:

  • Commonly called “Template Strings”, as this was their name in prior editions of ES2015 / ES6 specification.

    通常被稱為“模板字符串”,因為它是ES2015 / ES6規范的先前版本中的名稱。
  • Variables and parameters need to be wrapper in dollar sign and curly braces, ie. placeholder ${EXAMPLE}.

    變量和參數需要用美元符號和大括號括起來,即。 占位符 $ {EXAMPLE}。

  • The plus sign,“+”, inside of a Template Literal literally acts as a math operation, not a concatenation if also inside ${}. See examples below for further explanation.

    模板文字內部的加號“ +”實際上是數學運算,如果在$ {}內,則不是串聯。 請參閱下面的示例以獲取更多說明。

遷移到模板文字語法 (Migrating to Template Literal Syntax)

After reviewing the benefits and items to be aware of, take note of these examples and study the subtle differences with using Template Literals:

在審查了要注意的好處和事項之后,請注意以下示例,并研究使用Template Literals的細微差別:

// #1
// Before:
function sayHi(petSquirrelName) { console.log('Greetings ' + petSquirrelName + '!'); }
sayHi('Brigadier Sir Nutkins II'); // => Greetings Brigadier Sir Nutkins II!// After:
function sayHi(petSquirrelName) { console.log(`Greetings ${petSquirrelName}!`); }
sayHi('Brigadier Sir Nutkins II'); // => Greetings Brigadier Sir Nutkins II!// #2
// Before:
console.log('first text string \n' + 'second text string'); 
// => first text string 
// => second text string// After:
console.log(`first text string 
second text string`); 
// => first text string 
// => second text string// #3
// Before:
var num1 = 5;
var num2 = 10;
console.log('She is ' + (num1 + num2) +  ' years old and\nnot ' + (2 * num1 + num2) + '.');
// => She is 15 years old and
// => not 20.// After:
var num1 = 5;
var num2 = 10;
console.log(`She is ${num1 + num2} years old and\nnot ${2 * num1 + num2}.`);
// => She is 15 years old and
// => not 20.// #4 
// Before:
var num1 = 12;
var num2 = 8;
console.log('The number of JS MVC frameworks is ' + (2 * (num1 + num2)) + ' and not ' + (10 * (num1 + num2)) + '.');
//=> The number of JS frameworks is 40 and not 200.// After:
var num1 = 12;
var num2 = 8;
console.log(`The number of JS MVC frameworks is ${2 * (num1 + num2)} and not ${10 * (num1 + num2)}.`);
//=> The number of JS frameworks is 40 and not 200.// #5
// The ${} works fine with any kind of expression, including method calls:
// Before:
var registeredOffender = {name: 'Bunny BurgerKins'};
console.log((registeredOffender.name.toUpperCase()) + ' you have been arrested for the possession of illegal carrot bits!');
// => BUNNY BURGERKINS you have been arrested for the possession of illegal carrot bits!// After:
var registeredOffender = {name: 'Bunny BurgerKins'};
console.log(`${registeredOffender.name.toUpperCase()} you have been arrested for the possession of illegal carrot bits!`);
// => BUNNY BURGERKINS you have been arrested for the possession of illegal carrot bits!

Let’s checkout an even more complex way of using Template Literals! Look at how easy it is to include all this information without worrying about all the “+” signs, spaces, math logic, and quotation placement! It can be so convenient! Also please note, you will need to include another dollar sign, outside of the placeholder, if printing out prices:

讓我們來看看使用模板文字的更復雜的方法! 看看包含所有這些信息有多么容易,而不必擔心所有的“ +”號,空格,數學邏輯和引號位置! 可以這么方便! 另請注意,如果打印出價格,則需要在占位符之外包含另一個美元符號:

function bunnyBailMoneyReceipt(bunnyName, bailoutCash) {var bunnyTip = 100;console.log(`Greetings ${bunnyName.toUpperCase()}, you have been bailed out!Total: $${bailoutCash}Tip: $${bunnyTip}------------Grand Total: $${bailoutCash + bunnyTip}We hope you a pleasant carrot nip-free day!  `);}bunnyBailMoneyReceipt('Bunny Burgerkins', 200);// Enter the above code into your console to get this result:
/* Greetings BUNNY BURGERKINS, you have been bailed out!Total: $200Tip: $100------------Grand Total: $300We hope you a pleasant carrot nip-free day! 
*/

Wow, so much simpler!! It’s so exciting…Ahh!!

哇,簡單得多! 太令人興奮了……啊!

點差運算符 (Spread Operators)

If you have multiple arguments in an array that you want to insert into a function call, or multiple arrays and/or array elements that you want to insert into another array seamlessly, use Spread Operators!

如果要在函數調用中插入的數組中有多個參數,或者要無縫插入到另一個數組中的多個數組和/或數組元素,請使用擴展運算符!

Benefits:

好處:

  • Easily concats arrays inside of other arrays.

    輕松在其他數組內合并數組。
  • Place the arrays wherever you want inside of that array.

    將陣列放置在該陣列內的任何位置。
  • Easily add arguments into function call.

    輕松將參數添加到函數調用中。
  • Just 3 dots ‘…’ before the array name.

    數組名稱前僅3個點“ ...”。
  • Similar to function.apply but can be used with the new keyword, while function.apply cannot.

    function.apply類似,但可以與new關鍵字一起使用,而function.apply不能。

Let’s take a look at a situation where we would want to add several arrays into another main array without using the Spread Operator:

讓我們看一下一種情況,我們希望不使用Spread運算符將幾個數組添加到另一個主數組中:

var squirrelNames = ['Lady Nutkins', 'Squirrely McSquirrel', 'Sergeant Squirrelbottom'];
var bunnyNames = ['Lady FluffButt', 'Brigadier Giant'];
var animalNames = ['Lady Butt', squirrelNames, 'Juicy Biscuiteer', bunnyNames];animalNames;
// => ['Lady Butt', ['Lady Nutkins', 'Squirrely McSquirrel', 'Sergeant Squirrelbottom'], 'Juicy Biscuiteer', ['Lady FluffButt', 'Brigadier Giant']]// To flatten this array we need another step:
var flattened = [].concat.apply([], animalNames);
flattened;
// => ['Lady Butt', 'Lady Nutkins', 'Squirrely McSquirrel', 'Sergeant Squirrelbottom', 'Juicy Biscuiteer', 'Lady FluffButt', 'Brigadier Giant']

With the Spread Operator, your arrays are automatically inserted and concatenated wherever you’d like. No need for any extra steps:

使用Spread運算符,可以將數組自動插入并連接到所需的位置。 無需任何其他步驟:

var squirrelNames = ['Lady Nutkins', 'Squirrely McSquirrel', 'Sergeant Squirrelbottom'];
var bunnyNames = ['Lady FluffButt', 'Brigadier Giant'];
var animalNames = ['Lady Butt', ...squirrelNames, 'Juicy Biscuiteer', ...bunnyNames];animalNames;
// => ['Lady Butt', 'Lady Nutkins', 'Squirrely McSquirrel', 'Sergeant Squirrelbottom', 'Juicy Biscuiteer', 'Lady FluffButt', 'Brigadier Giant']

Another useful example:

另一個有用的例子:

var values = [25, 50, 75, 100]// This:
console.log(Math.max(25, 50, 75, 100)); // => 100// Is the same as this:
console.log(Math.max(...values)); // => 100/* NOTE: Math.max() typically does not work for arrays unless you write it like:Math.max.apply(null, values), but with Spread Operators you can just insert itand voila! No need for the .apply() part! Wohoo! :)
*/

可能比.apply()更有用 (Potentially more useful than .apply())

What if you have multiple arguments to place inside of a function? You could use the good ol’ Function.prototype.apply:

如果要在函數內部放置多個參數怎么辦? 您可以使用良好的Function.prototype.apply

function myFunction(x, y, z) {console.log(x + y + z)
};
var args = [0, 1, 2];
myFunction.apply(null, args);
// => 3

Or use the Spread Operator:

或使用價差運算符:

function myFunction(x, y, z) {console.log(x + y + z);
}
var args = [0, 1, 2];
myFunction(...args);
// => 3

In ES5 it is not possible to compose the new keyword with the apply method. Since the introduction of the Spread Operator syntax, you can now!

在ES5中,不可能使用apply方法來組成new關鍵字。 自從引入Spread Operator語法以來,您現在就可以!

var dateFields = readDateFields(database);
var d = new Date(…dateFields);

發電機 (Generators)

Benefits:

好處:

  • Allows you to pause functions to be resumed later.

    允許您暫停要在以后恢復的功能。
  • Easier to create asynchronous functions.

    易于創建異步功能。
  • Used commonly with setTimeout() or setInterval() to time asynchronous events.

    通常與setTimeout()setInterval()一起使用以計時異步事件。

Be aware:

意識到:

  • You know you are looking at a generator if you see * and the word yield.

    如果您看到*和yield字樣,就知道您正在看發電機。

  • You need to call the function each time so the next function within is called, otherwise it won’t run, unless it’s within a setInterval().

    您需要每次都調用該函數,以便調用其中的下一個函數,否則它將不會運行,除非它在setInterval()中

  • Result naturally comes out in object form, add .value to get value only.

    結果自然以對象形式出現,添加。 只得到價值。

  • Object comes with done property that is set to false until all yield expressions are printed.

    對象帶有done屬性,該屬性設置為false,直到打印所有yield表達式。

  • Generators end either when all functions/values have been called or if a return statement is present.

    當所有函數/值都已被調用或存在return語句時,生成器結束。

Example:

例:

function* callMe() {yield '1';yield '…and a 2';yield '…and a 3';return;yield 'this won’t print';
}var anAction = callMe();console.log(anAction.next());
//=> { value: ‘1’, done: false }console.log(anAction.next());
//=> { value: ‘…and a 2’, done: false }console.log(anAction.next());
//=> { value: ‘…and a 3’, done: false }console.log(anAction.next());
//=> { value: ‘undefined’, done: true }console.log(anAction.next());
//=> { value: ‘undefined’, done: true }// NOTE: To get only the value use anAction.next().value otherwise the entire object will be printed.

Generators are super useful when it comes to asynchronous functions calls. Let’s say you have 3 different functions that you’ve stored in an array and you want to call each one after another after a certain amount of time:

對于異步函數調用,生成器非常有用。 假設您在數組中存儲了3個不同的函數,并且希望在一定時間后依次調用每個函數:

// Bunny needs to go grocery shopping for her friend’s birthday party.
var groceries = '';// Let’s create three functions that need to be called for Bunny.
var buyCarrots = function () {groceries += 'carrots';
}var buyGrass = function () {groceries += ', grass';
}var buyApples = function () {groceries += ', and apples';
}// Bunny is in a hurry so you have to buy the groceries within certain amount of time!
// This is an example of when you would use a timer with a Generator.
// First store the functions within an array:
var buyGroceries = [buyCarrots, buyGrass, buyApples];// Then loop through the array within a Generator:
// There are some issues doing this with the forEach, recreate this using a for loop.
function* loopThrough(arr) {for(var i=0; i<arr.length; i++) {yield arr[i]();}
}// add the array of three functions to the loopThrough function.
var functions = loopThrough(buyGroceries);// Lastly, set the time you want paused before the next function call 
// using the setInterval method(calls a function/expression after a specific set time).
var timedGroceryHunt = setInterval(function() {var functionCall = functions.next();if(!functionCall.done) {console.log(`Bunny bought ${groceries}!`);}else {clearInterval(timedGroceryHunt);console.log(`Thank you! Bunny bought all the ${groceries} in time thanks to your help!`);}
}, 1000);// Enter this code into your console to test it out!
// after 1 second: => Bunny bought carrots!
// after 1 second: => Bunny bought carrots, grass!
// after 1 second: => Bunny bought carrots, grass, and apples!
// after 1 second: => Thank you! Bunny bought all the carrots, grass, and apples in time thanks to your help!

This can similarly be accomplished via a promise (an operation that hasn’t completed yet, but is expected in the future) as well. Developers sometimes use promises and Generators together in their code, so it’s good to be aware of both.

同樣,這也可以通過一個諾言來完成(一個尚未完成的操作,但有望在將來進行)。 開發人員有時在他們的代碼中同時使用promise和Generators,因此最好同時意識到兩者。

Congrats! You’ve made it through Learn ES6 The Dope Way Part III and now you’ve acquired three super valuable concepts! You can now safely brush up and make efficient use of Template Literals, Spread Operators, and Generators within your code. Woohoo! Go you!

恭喜! 您已經通過Learn ES6 The Dope Way Part III取得了成功,現在您已經獲得了三個非常有價值的概念! 現在,您可以安全地重新編寫代碼,并有效利用代碼中的模板文字,擴展運算符和生成器。 hoo! 去吧!

Although, you might want to wait since there are still browser issues with ES6 and it’s important to use compilers like Babel or a module bundler like Webpack before publishing your code. All of these will be discussed in future editions of Learn ES6 The Dope Way! Thanks for reading ?

雖然,您可能要等待,因為ES6仍然存在瀏覽器問題,在發布代碼之前使用Babel這樣的編譯器或Webpack這樣的模塊捆綁程序很重要。 所有這些將在Learn ES6 The Dope Way的未來版本中進行討論 感謝您閱讀 ?

Keep your wisdom updated by liking and following as more Learn ES6 The Dope Way is coming soon to Medium!

通過喜歡和關注更多來保持您的智慧更新。 了解ES6涂料之路即將成為中型!

Part I: const, let & var

第一部分:const,let和var

Part II: (Arrow) => functions and ‘this’ keyword

第二部分:(箭頭)=>函數和“ this”關鍵字

Part III: Template Literals, Spread Operators & Generators!

第三部分:模板文字,傳播運算符和生成器!

Part IV: Default Parameters, Destructuring Assignment, and a new ES6 method!

第四部分:默認參數,解構分配和新的ES6方法!

Part V: Classes, Transpiling ES6 Code & More Resources!

第五部分:類,轉譯ES6代碼及更多資源!

You can also find me on github ? https://github.com/Mashadim

您也可以在github?https ://github.com/Mashadim上找到我

翻譯自: https://www.freecodecamp.org/news/learn-es6-the-dope-way-part-iii-template-literals-spread-operators-generators-592765337294/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/396281.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/396281.shtml
英文地址,請注明出處:http://en.pswp.cn/news/396281.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Jenkins --SVN

項目名稱&#xff1a;XXX 源碼管理&#xff1a; None 發布之前&#xff0c;獲取源碼 編譯獲取后的代碼&#xff0c;指定vs版本 將源碼拷貝至jenkins工作控件 d:\jenkins\workspace\.. 刪除指定文件 用管理員命令 將Jenkins工作空間的代碼發布至指定路徑轉載于:https://www.cnbl…

keil5圖標變成白色_電腦桌面圖標全部變成白色的解決辦法

系統桌面圖標全部變成一個樣子的白色圖標&#xff0c;這是怎么回事&#xff1f;電腦桌面的圖標全部變成白色該如何解決&#xff1f;下面為大家解答。解決辦法&#xff1a;1.首先嘗試最簡單的方法操作看看&#xff0c;登錄到系統桌面&#xff0c;右鍵桌面空白處點擊打開“個性化…

java 繪圖球的移動_求助在JFrame上繪制移動的小球

我想在JFrame中或者Frame中添加一張背景圖片&#xff0c;然后在這圖片上畫出會移動的小球&#xff0c;怎么實現&#xff1f;我的代碼把添加背景圖片去掉&#xff0c;小球就正常運行了&#xff0c;怎么修改啊&#xff1f;希望各位大俠指教不勝感激&#xff01;&#xff01;&…

apache mesos_試用Apache Mesos HTTP API獲得樂趣和收益

apache mesosby Marco Massenzio由Marco Massenzio 試用Apache Mesos HTTP API獲得樂趣和收益 (Experimenting with the Apache Mesos HTTP API for Fun and Profit) Apache Mesos is a tool used in production at large-scale services like Twitter and Airbnb. Here’s it…

epoll哪些觸發模式_5.epoll的水平觸發和邊緣觸發

本篇是多路復用的第五篇&#xff0c;主要來講解epoll的水平觸發和邊緣觸發是怎么回事。一、概念介紹EPOLL事件有兩種模型&#xff0c;水平出發和邊緣觸發&#xff0c;如下所示&#xff1a;1. Level Triggered (LT) 水平觸發1. socket接收緩沖區不為空 有數據可讀 讀事件一直觸發…

HC系列藍牙模塊連接單片機與電腦,傳輸數據(藍牙心電測試)

畢設做無線心電監護。有線的做出來了&#xff0c;AD8232MCULabVIEW上位機。pcb還沒時間搞&#xff0c;這個9*7*2.5cm拿來測試能用。 自己做了AD8232的模擬前端&#xff0c;打的板子還沒到沒法測試。 雖然比較水&#xff0c;但看起來任務也完成的差不多了&#xff0c;于是就想加…

java實現社交平臺_GitHub - akpaul9527/symphony: 一款用 Java 實現的現代化社區(論壇/BBS/社交網絡/博客)平臺。...

下一代的社區系統&#xff0c;為未來而構建簡介Symphony([?s?mf?ni]&#xff0c;n.交響樂)是一個現代化的社區平臺&#xff0c;因為它&#xff1a;實現了面向內容討論的論壇實現了面向知識問答的社區包含了面向用戶分享、交友、游戲的社交網絡100% 開源動機很多社區論壇系統…

遠程連接本地mongodb 數據庫

綁定本地IP即可 start mongod --dbpath D:\mongodb\data\db --bind_ip 192.168.31.143 轉載于:https://www.cnblogs.com/yang-xiansen/p/9884598.html

qt日志實現

qt的日志有四個級別&#xff1a;qDebug&#xff1a; 調試信息qWarning&#xff1a; 警告信息qCritical&#xff1a; 嚴重錯誤qFatal&#xff1a; 致命錯誤可以通過<QtGlobal>下的void qCritical ( const char * msg, ... );void qDebug ( const char *…

mvc 視圖和模型的對應_通過在酒吧訂購飲料來解釋模型視圖控制器(MVC)

mvc 視圖和模型的對應by Kevin Kononenko凱文科諾年科(Kevin Kononenko) 通過在酒吧訂購飲料來解釋模型視圖控制器(MVC) (Model-View-Controller (MVC) Explained Through Ordering Drinks At The Bar) 如果您去過酒吧&#xff0c;那么MVC并不難。 (If you have been to a bar…

nodejs計算時間間隔_Javascript計算時間差的函數分享

核心代碼/** 獲得時間差,時間格式為 年-月-日 小時:分鐘:秒 或者 年/月/日 小時&#xff1a;分鐘&#xff1a;秒* 其中&#xff0c;年月日為全格式&#xff0c;例如 &#xff1a; 2010-10-12 01:00:00* 返回精度為&#xff1a;秒&#xff0c;分&#xff0c;小時&#xff0c;天*…

jQuery實現鼠標劃過展示大圖的方法

這篇文章主要介紹了jQuery實現鼠標劃過展示大圖的方法,實例分析了jQuery操作鼠標事件及圖片處理的技巧,具有一定參考借鑒價值,需要的朋友可以參考下 本文實例講述了jQuery實現鼠標劃過展示大圖的方法。分享給大家供大家參考。具體如下&#xff1a; 這里用css和jquery實現鼠標移…

精通java益處_你真的精通Java嗎?

簡歷和自我介紹上經常能夠讀到“精通Java”這樣的話&#xff0c;有人和我說&#xff0c;精通Java的人太多了&#xff0c;精通Java已經不能算亮點、不能給自己加分了。可是事實真是這樣嗎&#xff1f;對于語言的學習&#xff0c;我有一種觀點&#xff0c;一是縱向&#xff0c;即…

Luogu P2101 命運石之門的選擇(分治+搜索)

P2101 命運石之門的選擇 題意 題目描述 在某一條不知名世界線的岡倫今天突然接到了一條\(dmail\)&#xff0c;上面說世界線將會發生巨大變動&#xff0c;未來的他無論如何都無法扭轉這種變動回到原來的世界線。而世界線變動的原因是現在的他不久后錯過了與助手的約會。他約好要…

Java初級筆記-第五章

第五章 面向對象的特點 5.1 繼承 面向對象的重要特點之一就是繼承。類的繼承使得能夠在已有的類的基礎上構造新的類&#xff0c;新類除了具有被繼承類的屬性和方法外&#xff0c;還可以根據需要添加新的屬性和方法。繼承有利于代碼的復用&#xff0c;通過繼承可以更有效地組織程…

取模運算性質_求余、取模運算在RTOS中計算優先級的理解

uCOS3中的部分源碼&#xff1a;/* 置位優先級表中相應的位 */void OS_PrioInsert (OS_PRIO prio){CPU_DATA bit;CPU_DATA bit_nbr;OS_PRIO ix;/* 求模操作&#xff0c;獲取優先級表數組的下標索引 */ix prio / DEF_INT_CPU_NBR_BITS;//32bits//由于數據均為無符號數,prio為8位…

歸結原則_被聘為自由職業者歸結為一件事:信任。

歸結原則by I quit Medium我退出Medium 被聘為自由職業者歸結為一件事&#xff1a;信任。 (Getting hired as a freelancer comes down to one thing: trust.) When I ask freelancers what they think is the most important factor in landing a client project, they usual…

關于JS的傳遞方式的小理解

var test function() {//將其看成是創建了一個對象alert(1);}var otherTest test;//賦值導致test和otherTest指向同一個對象otherTest();test.sd 9;//對對象進行操作&#xff0c;兩者都發生改變alert(otherTest.sd);//9var test function() {//test重新創建了一個對象&…

java p代表哪種數據類型_java數據類型(八種基本數據類型+三種引用類型)

1、整型類型 占用字節 取值范圍byte 1 -128~127 (7次方)short 2 -32 768~32 767 (15次方)int …

python中的隨機函數

python--隨機函數&#xff08;random,uniform,randint,randrange,shuffle,sample&#xff09; 本文轉載自:[chamie] random() random()方法&#xff1a;返回隨機生成的一個實數&#xff0c;它在[0,1)范圍內 運用random()方法的語法&#xff1a; import random #random()方法不…