为什么我的array.forEach()没有中断迭代并返回“ true”?

时间:2018-10-31 15:27:25

标签: javascript foreach boolean-logic

我正在尝试编写一个比较数组中的值以查看它们是否与常量“ flightValue”匹配的函数。但是,即使返回“ true”值,循环也不会停止并最终返回未定义的值。

我在这里的逻辑中断了什么?

// Write a function that takes an integer flightLength (in minutes) and an array of integers movieLengths (in minutes) and returns a boolean indicating whether there are two numbers in movieLengths whose sum equals flightLength.

let moviesArray = [75, 120, 65, 140, 80, 95, 45, 72];

function canWatchTwoMovies(flightLength, array) {
  let startIndex = 0;
  let endIndex = array.length;

  array.forEach((el, index)=> {
    let currentPointer = index;
    for(i = currentPointer+1; i < endIndex; i++) {
      if(array[currentPointer] + array[i] == flightLength) {
        // Uncomment the console.log to see that there is a 'true' value
        // console.log(array[currentPointer] + array[i] == flightLength);
        // Why is this not breaking the loop and returning "true"?
        return true;
      }
    }
  });
  // I have commented out the default return value
  // return false;
  console.log("The function doesn't break and always runs to this point");
}

// Should return 'true' for addition of first two elements '75' and '120'
canWatchTwoMovies(195, moviesArray);

编辑: 以下是根据Maor Refaeli的回复整理的代码:

function canWatchTwoMovies(flightLength, array) {
  for (let index = 0; index < array.length; index++) {
    let currentPointer = index;
    for(let i = currentPointer+1; i < array.length; i++) {
      if(array[currentPointer] + array[i] == flightLength) {
        return true;
      }
    }
  }
  return false;
}

1 个答案:

答案 0 :(得分:1)

使用global-project/stack.yaml时,您将声明一个将对数组中每个项目执行的函数。
一种实现所需目标的方法是使用for循环:

forEach