2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: 587d7b88367417b2b2512b46
|
|
|
|
challengeType: 1
|
2020-08-04 15:13:35 +08:00
|
|
|
forumTopicId: 301209
|
2018-10-10 18:03:03 -04:00
|
|
|
localeTitle: 设置函数的默认参数
|
|
|
|
---
|
|
|
|
|
|
|
|
## Description
|
2020-08-04 15:13:35 +08:00
|
|
|
<section id='description'>
|
|
|
|
ES6 里允许给函数传入<dfn>默认参数</dfn>,来构建更加灵活的函数。
|
|
|
|
请看以下代码:
|
|
|
|
|
|
|
|
```js
|
|
|
|
const greeting = (name = "Anonymous") => "Hello " + name;
|
|
|
|
|
|
|
|
console.log(greeting("John")); // Hello John
|
|
|
|
console.log(greeting()); // Hello Anonymous
|
|
|
|
```
|
|
|
|
|
|
|
|
默认参数会在参数没有被指定(值为 undefined )的时候起作用。在上面的例子中,参数<code>name</code>会在没有得到新的值的时候,默认使用值 "Anonymous"。你还可以给多个参数赋予默认值。
|
|
|
|
</section>
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
## Instructions
|
2020-08-04 15:13:35 +08:00
|
|
|
<section id='instructions'>
|
|
|
|
给函数<code>increment</code>加上默认参数,使得在<code>value</code>没有被赋值的时候,默认给<code>number</code>加1。
|
|
|
|
</section>
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
## Tests
|
|
|
|
<section id='tests'>
|
|
|
|
|
|
|
|
```yml
|
|
|
|
tests:
|
2020-08-04 15:13:35 +08:00
|
|
|
- text: <code>increment(5, 2)</code>的结果应该为<code>7</code>。
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert(increment(5, 2) === 7);
|
2020-08-04 15:13:35 +08:00
|
|
|
- text: <code>increment(5)</code>的结果应该为<code>6</code>。
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert(increment(5) === 6);
|
2020-08-04 15:13:35 +08:00
|
|
|
- text: 参数<code>value</code>的默认值应该为<code>1</code>。
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert(code.match(/value\s*=\s*1/g));
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Challenge Seed
|
|
|
|
<section id='challengeSeed'>
|
|
|
|
|
|
|
|
<div id='js-seed'>
|
|
|
|
|
|
|
|
```js
|
2020-08-04 15:13:35 +08:00
|
|
|
const increment = (number, value) => number + value;
|
|
|
|
|
2018-10-10 18:03:03 -04:00
|
|
|
console.log(increment(5, 2)); // returns 7
|
|
|
|
console.log(increment(5)); // returns 6
|
|
|
|
```
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Solution
|
|
|
|
<section id='solution'>
|
|
|
|
|
|
|
|
```js
|
2020-08-04 15:13:35 +08:00
|
|
|
const increment = (number, value = 1) => number + value;
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
2020-08-04 15:13:35 +08:00
|
|
|
|
2018-10-10 18:03:03 -04:00
|
|
|
</section>
|