首页 > 解决方案 > 如何累积每个数字?JavaScript

问题描述

这是我的问题 我很难解决这个问题 任务:我们将向您传递一个包含两个数字的数组。返回这两个数字的总和加上它们之间所有数字的总和。最低的数字并不总是排在第一位。

For example, sumAll([4,1]) should return 10 because
sum of all the numbers between 1 and 4 (both inclusive) is 10.

function sumAll(arr) {
  Math.min(arr); //finds the lowest number and takes it 1
  Math.max(arr); //finds the largest number 4
  //must start at the 1st number and loops over until the max value is reached
  //0 start at the 0th index of the array 
  //++ increament by one so 1 2 3 4 
  //multiply's each number
  //.lenght until the lenght of the array is reached
  var i;
  for (i = 0; i < arr.length; i++) {
    i * i;
  }
  return 1;
}

sumAll([1, 4]);

标签: javascriptloopsmaxmin

解决方案


如果数组中总是有 2 个数字,那么您可以轻松地做到这一点,而无需更多花哨的代码。

var arr = [1, 4];
arr.sort((a, b) => a - b);
var total = 0;
for (var i = arr[0]; i <= arr[1]; i++ ) {
     total += i;
}

console.log(total);

推荐阅读