es6 方法默认参数_了解ES6涂料方式第四部分:默认参数,销毁分配和新方法!...

es6 方法默认参数

by Mariya Diminsky

通过玛丽亚·迪明斯基(Mariya Diminsky)

了解ES6涂料方式第四部分:默认参数,销毁分配和新方法! (Learn ES6 The Dope Way Part IV: Default Parameters, Destructuring Assignment, and a new method!)

Welcome to Part IV of Learn ES6 The Dope Way, a series created to help you easily understand ES6 (ECMAScript 6)!

欢迎来到学习ES6的第四部分, Dope Way ,该系列旨在帮助您轻松理解ES6(ECMAScript 6)!

Today let’s explore two new ES6 concepts and introduce a new method!

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

  • Default Function Parameters

    默认功能参数
  • Destructuring Assignment

    销毁分配
  • A New ES6 Method ❤

    新的ES6方法❤
默认功能参数 (Default Function Parameters)

Benefits:

好处:

  • Useful for situations when you need default values in a function.

    在需要在函数中使用默认值的情况下很有用。
  • When undefined is passed in, it will still use the default value instead!

    当传入undefined时,它将仍然使用默认值!

Beware:

谨防:

  • If you set a function as a default value inside of another function, it will throw a ReferenceError

    如果将一个函数设置为另一个函数内部的默认值,它将抛出ReferenceError
  • The location of your input values, when you call a function, will affect whether you reach the parameter with the default value. For example, if you had two parameters and wanted to reach the second parameter, you would only enter one item in the function you are calling. Since the second parameter would be missing the default value would appear there. See examples below for further explanation.

    调用函数时,输入值的位置将影响是否使用默认值到达参数。 例如,如果您有两个参数并想到达第二个参数,则只需在要调用的函数中输入一项。 由于第二个参数将丢失,因此默认值将出现在此处。 请参阅下面的示例以获取更多说明。

If you’ve ever wanted to create a function that would have default values as a backup…CONGRATULATIONS! This glorious day has finally arrived!

如果您曾经想创建一个具有默认值的函数作为备份...恭喜! 这光荣的一天终于到了!

Default function parameters allow you to initialize default values if either no values are passed, or if undefined is passed. Before, if you had something like this:

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

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

You would get NaN, not a number. But now you can do this:

您会得到NaN ,而不是数字。 但是现在您可以执行以下操作:

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

You get 12! This means if you don’t specifically add values to this function when you call it, it will use the default values. So you can also do this:

你得到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.

The overwriting of default values will occur based on the position in which you enter your input values when you call the function. For example:

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

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)

When passing undefined values, the default value is still chosen:

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

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

If no default value is assigned for a parameter, it will just return undefined, as normal:

如果没有为参数分配默认值,则它将正常返回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!
销毁分配 (Destructuring Assignment)

Benefits:

好处:

  • Extracts data from arrays and objects and assigns them to variables

    从数组和对象中提取数据并将其分配给变量
  • Simplifies the amount of keystrokes needed, and improves readability

    简化了所需的击键次数,并提高了可读性
  • Super useful when needing to pass in large amount of data with the same properties (such as user profiles)

    需要传递具有相同属性(例如用户配置文件)的大量数据时超级有用

Beware:

谨防:

  • Can be a bit complicated to understand in the beginning, but once you understand its benefits, just review the examples provided and research further. You’ll get the hang of it! :)

    刚开始理解起来可能有点复杂,但是一旦了解了它的好处,只需回顾提供的示例并进一步研究。 您将掌握一切! :)

Let’s take a step back and learn about Destructuring Assignment, and how it’s used in relation to Arrays, Objects, and even in combination with Default Parameters!

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

First, let’s practice with arrays by creating an array of Bunny’s favorite food. We could access the first and fifth item in the array the traditional way:

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

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

Or we could use Destructuring Assignment! We do this by removing the variable name and passing in a bracket that will point to what items we want in the array when we call it:

或者我们可以使用解构分配! 我们通过删除变量名称并传递一个括号来做到这一点,当我们调用它时,它将指向我们想要在数组中的哪些项目:

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

Whoa whoa whoa! What just happened? Where is our Papaya?

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

AHA! Got you there!

啊! 到那里去!

Check this out — firstItem and fifthItem are just words. The real trick here is where they are placed. The location of the word you place in the brackets will correspond to the location of the item you want in the array.

检查了这一点-并与firstItemfifthItem只是文字。 真正的窍门是放置它们的位置。 放在括号中的单词的位置将与您要在数组中的项目的位置相对应。

This is why the first word in the brackets — firstItem — corresponds to the first item in the array ‘Carrots’’ and the second word—fifthItem — corresponds to the second item in the array, ‘Carrot Bits’.

这就是为什么方括号中的第一个单词firstItem对应于数组“ Carrots ”中的第一项,而第二个字Five-Item对应于数组“ Carrot Bits ”中的第二项。

Here’s how to get access to a different location with the same word:

以下是使用相同字词访问其他位置的方法:

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

Play around with this code in your console so you can better understand this new concept, and tell us all in the comments section what you find. :)

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

Ok, we’ve got arrays down, so now how about Destructuring Assignment with objects? Let’s first check out the typical way we access items in an object:

好的,我们已经减少了数组,那么现在如何用对象分解分配呢? 首先让我们看看访问对象中项目的典型方式:

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’

Now let’s destructure this object using a similar approach to what we used with arrays . Take away the variable name and in it’s place, put curly braces — as this is an object — just like we did brackets for arrays.

现在,让我们使用与arrays相似的方法来分解该对象。 删除变量名,并在其位置放大括号(因为这是一个对象),就像我们对数组做括号一样。

Inside the curly braces, pass in the object properties that we’ll want access to:

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

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'

Here’s a slightly more complicated but useful way of using Destructuring:

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

Let’s say you have a function that you want to gain access to all the objects with the same properties but different values. This can be especially useful for large data sets, such as user profiles. But in this example we will use Bunny’s favorite things to make the concept clear:

假设您有一个函数想要访问具有相同属性但值不同的所有对象。 这对于大型数据集(例如用户配置文件)特别有用。 但是在此示例中,我们将使用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!

So what just happened?

那到底发生了什么?

When we passed in our objects(iceCream, sushi, fruit), the favThings function parsed it and allowed us to access these properties because we used same property names in each object.

当我们传入对象(冰淇淋,寿司,水果)时,favThings函数将其解析并允许我们访问这些属性,因为我们在每个对象中使用了相同的属性名称。

将解构分配与默认参数结合 (Combining Destructuring Assignment with Default Parameters)

Study the example below:

研究以下示例:

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!

Or if you had an object and array ready for Destructuring:

或者,如果您已准备好进行分解的对象和数组:

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方法❤ (A New ES6 Method ❤)

Benefits:

好处:

  • Repeat strings without using your own algorithm

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

Beware:

谨防:

  • Negative numbers and infinity will cause a RangeError

    负数和无穷大会导致RangeError

  • Decimal Numbers will be rounded down to an integer

    小数将四舍五入为整数

Ever seen that algorithm, the one that you usually get when you first start learning algorithms and it asks you to repeat a word/string several times?

您是否见过那种算法,当您第一次开始学习算法时通常会得到这种算法,它要求您重复一个单词/字符串几次?

CONGRATULATIONS!

恭喜!

Your string-repeating-algorithm days are over!

您的字符串重复算法天已经过去了!

Introducing the new repeat.() method brought to you by ES6!

介绍ES6带给您的新的repeat。()方法!

Here’s how it works:

运作方式如下:

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

Though if you’re reading this and you’re learning algorithms or haven’t started learning them yet, I would highly advise to actually create a function for repeating a string and not using this method since that would defeat the purpose of learning and solving challenges. Once you got it down, go ahead and use this method to your heart’s content. YIPEE!

尽管如果您正在阅读本文,并且正在学习算法或尚未开始学习算法,我强烈建议您实际创建一个用于重复字符串的函数,而不要使用此方法,因为这样做会破坏学习和求解的目的挑战。 一旦发现问题,请继续使用此方法来满足您的需求。 耶!

Congrats! You’ve made it through Learn ES6 The Dope Way Part IV and now you’ve acquired two super important ES6 concepts: Default Function Parameters and Destructuring Assignment, as well as learned a fun new method for repeating a string! Yay! Go you!

恭喜! 您已经通过学习ES6 The Dope Way Part IV取得了成功,现在您已经获得了两个非常重要的ES6概念:默认函数参数和解构赋值,并且学习了一种有趣的重复字符串的新方法! 好极了! 去吧!

Remember that if you want to use ES6, there are still browser compatibility issues, so 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-iv-default-parameters-destructuring-assignment-a-new-es6-method-44393190b8c9/

es6 方法默认参数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值