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/

了解ES6 The Dope Way第三部分:模板文字,扩展运算符和生成器!相关推荐

  1. ES6 | let 关键字 + const关键字 + 箭头函数 + rest参数 + 扩展运算符 ... + Symbol + 迭代器 + 生成器 + 变量的解构赋值 + 模板字符串

    目录 ECMASript 相关介绍 ECMASript 6 新特性 let 关键字 const关键字 变量的解构赋值 模板字符串 简化对象写法 箭头函数 => 参数默认值 rest参数 扩展运算 ...

  2. ES6——扩展运算符/三点运算符(...)

    扩展运算符(spread)是三个点(...). 数组的扩展运算符 对于数组来说,它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列. console.log(...[1, 2, 3]) ...

  3. es6之三个点(...) 扩展运算符数组和对象的使用场景及最常见的用法(霸霸看了都说好)

    概念 es6之扩展运算符 (-) 简称三个点 数组的扩展运算符应用 复制数组 扩展运算符提供了复制数组的简便写法. const a1 = [1, 2]; // 写法一 const a2 = [...a ...

  4. ES6 入门教程 9 数组的扩展 9.1 扩展运算符

    ES6 入门教程 ECMAScript 6 入门 作者:阮一峰 本文仅用于学习记录,不存在任何商业用途,如侵删 文章目录 ES6 入门教程 9 数组的扩展 9.1 扩展运算符 9.1.1 含义 9.1 ...

  5. ES6——扩展运算符的作用以及使用场景

    文章目录 对象扩展运算符 解构赋值 扩展运算符 数组扩展运算符 替代函数的apply() 方法 扩展运算符的应用 复制数组 合并数组 与解构赋值结合 字符串 实现了Iterator接口的对象 对象扩展 ...

  6. 了解ES6 The Dope Way Part II:Arrow功能和'this'关键字

    by Mariya Diminsky 通过玛丽亚·迪明斯基(Mariya Diminsky) 了解ES6 The Dope Way Part II:Arrow功能和'this'关键字 (Learn E ...

  7. 了解ES6 The Dope Way第五部分:类,转译ES6代码和更多资源!

    by Mariya Diminsky 通过玛丽亚·迪明斯基(Mariya Diminsky) 了解ES6 The Dope Way第五部分:类,转译ES6代码和更多资源! (Learn ES6 The ...

  8. 学习ES6 The Dope Way Part I:const,let&var

    by Mariya Diminsky 通过玛丽亚·迪明斯基(Mariya Diminsky) 学习ES6 The Dope Way Part I:const,let&var (Learn ES ...

  9. ES6(三)数组的扩展

    1.Array.form ES6中,Array.from = function(items,mapfn,thisArg) {  }   Array.from 用于将 类数组 和 可遍历对象(实现了It ...

最新文章

  1. Servlet3.0学习总结(三)——基于Servlet3.0的文件上传
  2. Java Math的 floor,round和ceil的总结 ,java基础知识
  3. 机器学习实战(五)——Logistic 回归
  4. muduo网络库源码阅读Step by Step
  5. 《Python Cookbook 3rd》笔记(1.19):转换并同时计算数据
  6. sea 配置资料收集
  7. jmeter 线程执行顺序_软件接口测试工具Jmeter使用方法详解(一)
  8. SQL那些事儿(十四)--C#调用oracle存储过程(查询非查询and有参无参)深度好文
  9. Debian 9.6.0 + OpenMediaVault 4.x : 实机安装前的虚拟机试验
  10. 【Vue源码】Vue中DOM的异步更新策略以及nextTick机制
  11. IC卡读写器c#源码
  12. mcgs组态软件中字体如果从左到右变化_MCGS脚本程序 (2)
  13. Bmob后台云数据库
  14. Mac苹果电脑没有声音怎么办
  15. Oracle 服务器连不上解决方式(远程telnet 1521端口失败)
  16. android bitmap nv21,Nv21转Bitmap(高效率转化)
  17. 激活 MarkDownPad 2
  18. Rook下快速部署ceph分布式文件系统
  19. Kali自带屏幕截图功能
  20. 计算机CCT考试模拟操作题,基础计算机cct考试模拟题.doc

热门文章

  1. 【UOJ 92】有向图的强连通分量
  2. 利用yii2 gridview实现批量删除案例
  3. delphi Post数据到网页
  4. Cppunit 源码 SynchronizedObject
  5. 方法性能分析器--装饰者模式应用
  6. SQL Server 2000 JDBC驱动的完整安装及测试说明
  7. Docker安装influxDB
  8. asp.net2.0跨域问题
  9. OWASP TOP 10 1
  10. Java 动态加载class 并反射调用方法