学习ES6 Dope Way第三部分:模板文字,传播运算符和生成器!

发布时间:2018-11-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了学习ES6 Dope Way第三部分:模板文字,传播运算符和生成器!脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

让我们进一步探索ES6并涵盖三个超级有价值的概念:

模板文字

优点:

  • 简单的表达式插值和方法调用!见下面的例子。
  • 以您想要的格式包含复杂信息很简单!
  • 您不必担心多个引号,多行,空格或使用“+”符号!只有两个后面的刻度识别它们内部的所有信息!哇噢!

  • 通常称为“模板字符串”,因为这是他们在ES2015 / ES6规范的先前版本中的名称。
  • 变量和参数需要包装在美元符号和花括号中,即。占位符 $ {EXamPLE}。
  • 模板文字内部的加号“+”字面意思是数学运算,而不是连接在$ {}内部的连接。有关详细说明,请参阅以下示例

迁移到模板文字语法

在查看了要注意的好处和项目后,请注意这些示例并使用模板文字来研究细微差别:

// #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!

让我们来看看使用模板文字的更复杂的方法吧!看看包含所有这些信息是多么容易,而不必担心所有的“+”符号,空格,数学逻辑和引用位置!它可以这么方便!另请注意,如果打印出价格,您需要在占位符之外添加另一个美元符号:

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: $200
      Tip: $100
      ------------
      Grand Total: $300
    
    We hope you a pleasant carrot nip-free day! 
*/

哇,这么简单!! 太令人兴奋......啊!

传播运营商

如果要在数组中有多个要插入函数调用的参数,或者要无缝插入另一个数组的多个数组和/或数组元素,请使用Spread运算符

优点:

  • 轻松地在其他数组中连接数组。
  • 将数组放在该数组中的任何位置。
  • 轻松地将参数添加到函数调用中。
  • 数组名称前只有3个点'...'。
  • function.apply类似,但可以与new关键字一起使用,而function.apply则不能。

让我们看一下我们想要在不使用Spread operator的情况下将几个数组添加到另一个主数组中的情况:

 
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']

使用SPRead Operator,您的阵列会自动插入并连接到您想要的任何位置。无需任何额外步骤:

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']

另一个有用的例子

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 it
        and voila! No need for the .apply() part! Wohoo! :)
*/

可能比.apply()更有用

@H_562_126@如果你有多个参数放在函数内部怎么办?你可以使用好的' Function.prototype.apply

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

或者使用Spread Operator:

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

ES5中,无法使用apply方法组合new关键字。自从引入Spread Operator语法以来,您现在就可以!

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

发电机

优点:

  • 允许您暂停稍后要恢复的功能。
  • 更容易创建异步功能。
  • 通常与setTimeout()setInterval()一起使用来计时异步事件。

意识到:

  • 如果你看到*和单词yield知道你正在看一个生成器。
  • 您需要每次调用该函数,以便调用其中的下一个函数,否则它将不会运行,除非它在setInterval()中
  • 结果自然以对象形式出现,添加。价值只能获得价值。
  • 对象带有done属性,在打印所有yield表达式之前,该属性设置为false 。
  • 生成器在调用所有函数/值或存在return语句时结束。

例:

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.

在异步函数调用方面,生成器非常有用。假设您有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!

这可以类似地通过承诺(尚未完成但未来预期的操作)来实现。开发人员有时会在他们的代码中一起使用promises和Generators,因此最好注意两者。

恭喜!你已经通过学习ES6 The Dope Way Part III实现了它,现在你已经获得了三个非常有价值的概念!您现在可以安全地刷新并有效地使用代码中的模板文字,扩展运算符和生成器。哇噢!去吧!

虽然,您可能要等待,因为ES6仍然存在浏览器问题,在发布代码之前使用像Babel这样的编译器或像Webpack这样的模块捆绑器很重要。所有这些将在学习ES6 The Dope Way的 未来版本中讨论

  觉得可用,就经常来吧!es6教程 脚本宝典 欢迎评论哦!巧夺天工,精雕玉琢。小宝典献丑了!

脚本宝典总结

以上是脚本宝典为你收集整理的学习ES6 Dope Way第三部分:模板文字,传播运算符和生成器!全部内容,希望文章能够帮你解决学习ES6 Dope Way第三部分:模板文字,传播运算符和生成器!所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。