学习ES6 Dope Way第四部分:默认参数,解构分配和新方法!

发布时间:2018-11-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了学习ES6 Dope Way第四部分:默认参数,解构分配和新方法!脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

欢迎来到Learn ES6 The DoPE Way的第四部分,这个系列旨在帮助您轻松理解ES6(ECMAScript 6)!

今天让我们探索两个新的ES6概念并介绍一种新方法!

默认功能参数

优点:

  • 适用于需要函数中的默认值的情况。
  • 不确定的传递中,它仍然会使用默认值,而不是!

  • 如果在另一个函数内部将函数设置为默认值,则会抛出一个ReferenceError
  • 调用函数时,输入值的位置将影响您是否使用默认值到达参数。例如,如果您有两个参数并想要到达第二个参数,则只能在要调用的函数中输入一个项目。由于缺少第二个参数,因此会出现默认值。有关详细说明,请参阅以下示例

如果你曾经想创建一个将默认值作为备份的函数......祝贺你!这个辉煌的一天终于来了!

如果未传递任何值,或者传递undefined,则默认函数参数允许您初始化默认值。以前,如果你有这样的事情:

function add(x, y) {
  console.LOG(x+y);
}
add(); // => NaN

你会得到NaN,而不是数字。但现在你可以这样做:

function add(x=5, y=7) {
  console.log(x+y);
}
add(); // => 12

你得到12!这意味着如果在调用它时没有专门为此函数添加值,它将使用默认值。所以你也可以这样做:

function add(x=5, y=7) {
  console.log(x+y);
}
add(12, 15); // => 27
add(); // => 12

// AND THIS:
function haveFun(action='burrowing', time=3) {
  console.log(`I will go ${action} wITh Bunny for ${time} hours.`)
}
haveFun(); // => I will go burrowing with Bunny for 3 hours.
haveFun('swimming', 2); // => I will go swimming with Bunny for 2 hours.

根据您调用函数时输入输入值的位置,将覆盖默认值。例如:

function multiply(a, b = 2) {
  return a*b;
}
multiply(3) // => 6 (returns 3 * 2)
multiply(5, 10) // => 50 (returns 5 * 10 since 10 replaces the default value)

传递未定义的值时,仍会选择默认值:

// test IT HERE: http://goo.gl/f6y1xb
function changeFontColor(elementId, color='blue') {
  document.getElementById(elementId).style.color = color;
}
changeFontColor('title') // => sets title to blue
changeFontColor('title', 'pink') // => sets title to pink
changeFontColor('title', undefined) // => sets title to blue

如果没有为参数分配默认值,它将像往常一样返回undefined:

function test(word1='HeyHeyHey', word2) {
  return `${word1} there, ${word2}!`
}
test(); // => HeyHeyHey there, undefined!

// IMPORTANT:
// In order to reach the second parameter and overwrite the default function,
// we need to include the First input as well:
test('Hi', 'Bunny') // => Hi there, Bunny!

解构分配

优点:

  • 数组和对象中提取数据并将它们分配给变量
  • 简化所需的击键量,并提高可读性
  • 当需要传递具有相同属性的大量数据(例如用户配置文件)时非常有用

谨防:

  • 开始可能有点复杂,但一旦了解了它的好处,只需查看提供的示例并进一步研究。你会得到它的立场!:)

让我们退后一步,了解解构分配,以及它如何与数组,对象一起使用,甚至与默认参数结合使用!

首先,让我们通过创建一个Bunny最喜欢的食物阵列来练习数组。我们可以用传统的方式访问数组中的第一个和第五个项目:

@H_105_126@
VAR BunnyFavFoods = ['Carrots', 'Carrot Bits', 'Grass', 'Berries', 'Papaya', 'Apples'];
console.log(BunnyFavFoods[0]) // => Carrots
console.log(BunnyFavFoods[4]) // => Papaya

或者我们可以使用Destructuring Assignment!我们通过删除变量名称并传入一个括号来执行此操作,该括号将在我们调用它时指向数组中我们想要的项目:

var [firstItem, fifthItem] = ['Carrots', 'Carrot Bits', 'Grass', 'Berries', 'Papaya', 'Apples'];
console.log(firstItem) // => Carrots
console.log(fifthItem) // => Carrot Bits

哇哇哇!刚刚发生了什么?我们的木瓜在哪里?

AHA!你到了!

看看这个 -  firstItemFifthItem只是单词。这里真正的诀窍是放置它们的位置。放在括号中的单词的位置将对应于数组中所需项目的位置。

这就是为什么括号中的第一个单词 -  firstItem - 对应于数组' Carrots '中的第一个项目,第二个单词- fifthItem -  对应于数组中的第二个项目' Carrot Bits '。

以下是如何使用相同的单词访问其他位置:

// Every additional comma added will rePResent the next item in the array.
var [firstItem,,,,fifthItem] = ['Carrots', 'Carrot Bits', 'Grass', 'Berries', 'Papaya', 'Apples'];
console.log(firstItem) // => Carrots
console.log(fifthItem) // => Papaya

// Wohoo! Let’s try some more! which item in the array will this get?
var [firstItem,,guessThisItem,,fifthItem] = ['Carrots', 'Carrot Bits', 'Grass', 'Berries', 'Papaya', 'Apples'];
console.log(firstItem) // => Carrots
console.log(guessThisItem) // => Grass
console.log(fifthItem) // => Papaya

// Are you noticing a pattern? One comma separates one word From another and 
// every additional comma before a word represents a place in the array.
// Ok, What would happen if we added a comma to the front?
var [,firstItem,,guessThisItem,,fifthItem] = ['Carrots', 'Carrot Bits', 'Grass', 'Berries', 'Papaya', 'Apples'];
console.log(firstItem) // => Carrot Bits
console.log(guessThisItem) // => Berries
console.log(fifthItem) // => Apples

// Everything moves one place over!
// And what if we moved everything back and added a word to the end?
var [firstItem,,guessThisItem,,fifthItem, whichOneami] = ['Carrots', 'Carrot Bits', 'Grass', 'Berries', 'Papaya', 'Apples'];
console.log(firstItem) // => Carrots
console.log(guessThisItem) // => Grass
console.log(fifthItem) // => Papaya
console.log(whichOneAmI) // => Apples

在控制台中使用此代码,以便更好地理解这个新概念,并在评论部分告诉我们您找到的所有内容。:)

好的,我们有阵列了,所以现在如何解析对象的分配?让我们首先看看我们访问对象中项目的典型方式:

var iceCream = {
  cost: 3.99,
  title: 'Ice Cream Flavors',
  type: ['chocolate', 'vanilla', 'caramel', 'strawberry', 'watermelon']
}

console.log(iceCream.cost, iceCream.title, iceCream.type[2]); 
//=> 3.99 ‘Ice Cream Flavors’ ‘caramel’

现在让我们使用与数组一样的方法来解构这个对象。拿走变量名称并在其中放置花括号 - 因为这是一个对象 - 就像我们为数组做括号一样。

在花括号内,传入我们想要访问的对象属性:

var {cost, title, type} = {
  cost: 3.99,
  title: 'Ice Cream Flavors',
  type: ['chocolate', 'vanilla', 'caramel', 'strawberry', 'watermelon']
}

// VOILA!
console.log(cost, title, type[2]) 
//=> 3.99 'Ice Cream Flavors' 'caramel'

这是使用Destructuring的一种稍微复杂但有用的方法:

假设您有一个函数要访问具有相同属性但值不同的所有对象。这对于大型数据集(例如用户配置文件)尤其有用。但在这个例子中,我们将使用Bunny最喜欢的东西来明确这个概念:

var iceCream = {
  cost: 3.99,
  name: 'Ice Cream Flavors',
  type: ['chocolate', 'vanilla', 'caramel', 'strawberry', 'watermelon']
}

var sushi = {
  cost: 5.99,
  name: 'Sushi Combinations',
  type: ['Eel Roll', 'Philadelphia Roll', 'Spicy Salmon Handroll', 'Rainbow Roll', 'Special Roll']
}

var fruit = {
  cost: 1.99,
  name: 'Fruits', 
  type: ['cherry', 'watermelon', 'strawberry', 'cantaloupe', 'mangosteen']
}

function favThings({cost, name, type}) {
  var randomNum = Math.floor((Math.random() * 4) + 1);
  console.log(`Bunny loves her ${name}! She especially loves ${type[randomNum]} for only $${cost}!`);
}

// RandoMLy generated for the type parameter.
// First time:
favThings(iceCream) // => Bunny loves her Ice Cream Flavors! She especially loves caramel for only $3.99!
favThings(sushi) // => Bunny loves her Sushi Combinations! She especially loves Philadelphia Roll for only $5.99!
favThings(fruit) // => Bunny loves her Fruits! She especially loves cantaloupe for only $1.99!

// Second time:
favThings(iceCream) // => Bunny loves her Ice Cream Flavors! She especially loves vanilla for only $3.99!
favThings(sushi) // => Bunny loves her Sushi Combinations! She especially loves Spicy Salmon Handroll for only $5.99!
favThings(fruit) // => Bunny loves her Fruits! She especially loves mangosteen for only $1.99!

// Try it in the console yourself and see what you get!

刚刚发生了什么?

当我们传入我们的对象(iceCream,sushi,fruit)时,favThings函数解析它并允许我们访问这些属性,因为我们在每个对象中使用相同的属性名称。

将解构分配与默认参数相结合

研究以下示例:

function profilePage({favColor: favColor} = {favColor: 'vintage pink'}, [name, age] = ['Bunny', 24]) {
  console.log(`My name is ${name}. I am ${age} years old and my favorite color is ${favColor}!`)
}

profilePage(); 
// => My name is Bunny. I am 24 years old and my favorite color is vintage pink!
profilePage({favColor: 'blue'}, ['Ed', 30]) 
// => My name is Ed. I am 30 years old and my favorite color is blue!

或者,如果您有一个对象和数组准备好进行解构:

var aboutEdward = {
  info: ['Edward', 30],
  favColor: 'blue',
  favSushiRoll: 'Squidy squid squid'
}

function profilePage({favColor} = {favColor: 'vintage pink'}, [name, age] = ['Bunny', 24]) {
  console.log(`My name is ${name}. I am ${age} years old and my favorite color is ${favColor}!`)
}
profilePage(); 
// => My name is Bunny. I am 24 years old and my favorite color is vintage pink!
profilePage(aboutEdward, aboutEdward.info); 
// => My name is Edward. I am 30 years old and my favorite color is blue!

一种新的ES6方法❤

优点:

  • 不使用自己的算法重复字符串

谨防:

  • 负数和无穷大将导致RangeError
  • 十进制数将向下舍入为整数

曾经见过这个算法,你第一次开始学习算法时通常得到的算法,并要求你多次重复一个单词/字符串?

恭喜!

你的字符串重复算法日结束了!

介绍ES6为您带来的新重复。()方法!

以下是它的工作原理:

// The general syntax: str.repeat(count);

// Examples:
'Bunny'.repeat(3); // => BunnyBunnyBunny
'Bunny'.repeat(2.5)// => BunnyBunny
'Bunny'.repeat(10/2) // => BunnyBunnyBunnyBunnyBunny
'Bunny'.repeat(-3) // => RangeError: Invalid count value
'Bunny'.repeat(1/0) // => RangeError: Invalid count value

虽然如果你正在读这个并且你正在学习算法或者还没有开始学习它们,我强烈建议实际创建一个函数来重复一个字符串而不使用这个方法,因为这会破坏学习和解决的目的挑战。一旦你把它弄下来,继续使用这种方法来满足你的内心。YIPEE!

恭喜!你已经通过学习ES6 The Dope Way Part IV来实现它,现在你已经获得了两个超级重要的ES6概念:默认函数参数和解构分配,以及学习一种有趣的重复字符串的新方法!好极了!去吧!

请记住,如果您想使用ES6,仍然存在浏览器兼容性问题,因此在发布代码之前,请使用像Babel这样的编译器或像Webpack这样的模块捆绑器。所有这些将在学习ES6 The Dope Way的 未来版本中讨论

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

脚本宝典总结

以上是脚本宝典为你收集整理的学习ES6 Dope Way第四部分:默认参数,解构分配和新方法!全部内容,希望文章能够帮你解决学习ES6 Dope Way第四部分:默认参数,解构分配和新方法!所遇到的问题。

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

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