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/