首页 > 解决方案 > 为什么我的 array.forEach() 没有中断迭代并返回“true”?

问题描述

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

我的逻辑在这里有什么突破?

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

标签: javascriptforeachboolean-logic

解决方案


使用时,forEach您声明了一个将为数组中的每个项目执行的函数。
实现您想要的一种方法是使用 for 循环:

// 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;

  for (let index = 0; index < array.length; i++) {
    let el = array[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);

推荐阅读