了解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.mzph.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()方法不…