freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../intermediate-algorithm-scri.../sum-all-numbers-in-a-range.md

1.6 KiB
Raw Blame History

id challengeType forumTopicId localeTitle
a3566b1109230028080c9345 5 16083 范围内的数字求和

Description

给出一个含有两个数字的数组,我们需要写一个函数,让它返回这两个数字间所有数字(包含这两个数字)的总和。

例如,sumAll([4,1]) 应该返回 10,因为从 1 到 4 (包含 1、4的所有数字的和是 10

如果你遇到了问题,请点击帮助

Instructions

Tests

tests:
  - text: <code>sumAll([1, 4])</code>应该返回一个数字。
    testString: assert(typeof sumAll([1, 4]) === 'number');
  - text: <code>sumAll([1, 4])</code>应该返回 10。
    testString: assert.deepEqual(sumAll([1, 4]), 10);
  - text: <code>sumAll([4, 1])</code>应该返回 10。
    testString: assert.deepEqual(sumAll([4, 1]), 10);
  - text: <code>sumAll([5, 10])</code>应该返回 45。
    testString: assert.deepEqual(sumAll([5, 10]), 45);
  - text: <code>sumAll([10, 5])</code>应该返回 45。
    testString: assert.deepEqual(sumAll([10, 5]), 45);

Challenge Seed

function sumAll(arr) {
  return 1;
}

sumAll([1, 4]);

Solution

function sumAll(arr) {
  var sum = 0;
  arr.sort(function(a,b) {return a-b;});
  for (var i = arr[0]; i <= arr[1]; i++) {
    sum += i;
  }
  return sum;
}