freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../intermediate-algorithm-scri.../arguments-optional.md

2.0 KiB

id challengeType forumTopicId title
a97fd23d9b809dac9921074f 5 14271 可选参数

Description

创建一个将两个参数相加的函数。如果只传入了一个参数,则返回一个函数,需要传入一个参数并返回总和。 比如,addTogether(2, 3)应该返回5。而addTogether(2)应该返回一个函数。 调用这个返回的函数,传入一个值,返回总和: var sumTwoAnd = addTogether(2); sumTwoAnd(3)此时应返回5。 只要其中任何一个参数不是数字,那就应返回undefined

Instructions

Tests

tests:
  - text: '<code>addTogether(2, 3)</code>应该返回5。'
    testString: assert.deepEqual(addTogether(2, 3), 5);
  - text: <code>addTogether(2)(3)</code>应该返回5。
    testString: assert.deepEqual(addTogether(2)(3), 5);
  - text: '<code>addTogether(&quot;http://bit.ly/IqT6zt&quot;)</code>应返回undefined。'
    testString: assert.isUndefined(addTogether("http://bit.ly/IqT6zt"));
  - text: '<code>addTogether(2, &quot;3&quot;)</code>应返回undefined。'
    testString: assert.isUndefined(addTogether(2, "3"));
  - text: '<code>addTogether(2)([3])</code>应返回undefined。'
    testString: assert.isUndefined(addTogether(2)([3]));

Challenge Seed

function addTogether() {
  return false;
}

addTogether(2,3);

Solution

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];
}