指数值总和至总计

时间:2020-12-27 20:01:06

标签: javascript arrays loops

我正在努力提高我的问题解决能力,并且很想得到一些关于我做错了什么的解释,或者我是否可以在正确的方向上有所帮助。我下面的代码是我所坚持的。

我的问题,我试图在数组中检查它是否包含总和为给定值的任何数字。非常简单,但对于初学者来说有点复杂。

我的第一步是设置一个函数,它有两个参数,接受我们想要的数组和总数。

const array = [10, 15, 7, 3];

function sumUpTotal(array, total) {
    
}

然后我想遍历我的数组以通过使用 forEach 方法输出每个值来检查数组中的每个值

const array = [10, 15, 7, 3];

function sumUpTotal(array, total) {
    array.forEach(value => value)
}

现在我有了所有的输出,我被困在如何检查这些数字是否相加以给出我们想要的总数。有人可以帮忙吗。

输出应该是两个数字之和。

例如,给定 [10, 15, 3, 7] 和 17 的 k,返回 true,因为 10 + 7 是 17。

1 个答案:

答案 0 :(得分:0)

您可以使用 Set 执行此操作,如下所示:

function sumUpTotal(array, total) {
  // initialize set
  const set = new Set();
  // iterate over array
  for(let i = 0; i < array.length; i++){
    // get element at current index
    const num = array[i];
    // get the remaining number from total
    const remaining = total - num;
    // if the remaining is already stored in the set, return numbers
    if(set.has(remaining)) return [num, remaining];
    // else add number to set
    else set.add(num);
  }
  // return null if no two numbers in array that sum up to total
  return null;
}

const array = [10, 15, 7, 3];
const total = 17;

console.log( sumUpTotal(array, total) );

相关问题