2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: a97fd23d9b809dac9921074f
|
|
|
|
title: Arguments Optional
|
|
|
|
challengeType: 5
|
2020-09-07 16:10:29 +08:00
|
|
|
forumTopicId: 14271
|
|
|
|
localeTitle: 可选参数
|
2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
|
|
|
|
## Description
|
2020-09-07 16:10:29 +08:00
|
|
|
<section id='description'>
|
|
|
|
创建一个将两个参数相加的函数。如果只传入了一个参数,则返回一个函数,需要传入一个参数并返回总和。
|
|
|
|
比如,<code>addTogether(2, 3)</code>应该返回<code>5</code>。而<code>addTogether(2)</code>应该返回一个函数。
|
|
|
|
调用这个返回的函数,传入一个值,返回总和:
|
|
|
|
<code>var sumTwoAnd = addTogether(2);</code>
|
|
|
|
<code>sumTwoAnd(3)</code>此时应返回<code>5</code>。
|
|
|
|
只要其中任何一个参数不是数字,那就应返回<code>undefined</code>。
|
|
|
|
</section>
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
## Instructions
|
2020-09-07 16:10:29 +08:00
|
|
|
<section id='instructions'>
|
|
|
|
|
2018-10-10 18:03:03 -04:00
|
|
|
</section>
|
|
|
|
|
|
|
|
## Tests
|
|
|
|
<section id='tests'>
|
|
|
|
|
|
|
|
```yml
|
|
|
|
tests:
|
|
|
|
- text: '<code>addTogether(2, 3)</code>应该返回5。'
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert.deepEqual(addTogether(2, 3), 5);
|
2018-10-10 18:03:03 -04:00
|
|
|
- text: <code>addTogether(2)(3)</code>应该返回5。
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert.deepEqual(addTogether(2)(3), 5);
|
2018-10-10 18:03:03 -04:00
|
|
|
- text: '<code>addTogether("http://bit.ly/IqT6zt")</code>应返回undefined。'
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert.isUndefined(addTogether("http://bit.ly/IqT6zt"));
|
2018-10-10 18:03:03 -04:00
|
|
|
- text: '<code>addTogether(2, "3")</code>应返回undefined。'
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert.isUndefined(addTogether(2, "3"));
|
2018-10-10 18:03:03 -04:00
|
|
|
- text: '<code>addTogether(2)([3])</code>应返回undefined。'
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert.isUndefined(addTogether(2)([3]));
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Challenge Seed
|
|
|
|
<section id='challengeSeed'>
|
|
|
|
|
|
|
|
<div id='js-seed'>
|
|
|
|
|
|
|
|
```js
|
|
|
|
function addTogether() {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
addTogether(2,3);
|
|
|
|
```
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Solution
|
|
|
|
<section id='solution'>
|
|
|
|
|
2020-09-07 16:10:29 +08:00
|
|
|
|
2018-10-10 18:03:03 -04:00
|
|
|
```js
|
2020-09-07 16:10:29 +08:00
|
|
|
function addTogether() {
|
|
|
|
var a = arguments[0];
|
|
|
|
if (toString.call(a) !== '[object Number]') return;
|
|
|
|
if (arguments.length === 1) {
|
|
|
|
return function(b) {
|
|
|
|
if (toString.call(b) !== '[object Number]') return;
|
|
|
|
return a + b;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
var b = arguments[1];
|
|
|
|
if (toString.call(b) !== '[object Number]') return;
|
|
|
|
return a + arguments[1];
|
|
|
|
}
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
2020-08-13 17:24:35 +02:00
|
|
|
|
2020-09-07 16:10:29 +08:00
|
|
|
</section>
|