首页 > 解决方案 > Javascript forEach 循环不会继续下一次迭代

问题描述

我正在尝试解决这个挑战,当元素任一侧的值之和相等时,函数应该返回元素的索引值。例如,[1,2,3,4,3,2,1] 应该返回 3,因为在 '4' 的另一侧,值加到 6 (1+2+3) 和 (3+2+1)。此外,如果没有这样的值,那么函数应该返回 -1。

function findEvenIndex(arr) {
  arr.forEach((element, index) => {
    let a = arr.splice(index + 1, arr.length); //array of values after current value
    let b = arr.splice(arr[0], index); //array of values before current value
    let suma = a.reduce((accumulator, currentValue) => { //Sum of array of after values
      return accumulator + currentValue;
    }, 0);
    let sumb = b.reduce((accumulator, currentValue) => { //Sum of array of before values
      return accumulator + currentValue;
    }, 0);
    if (suma === sumb) {  //comparing the two sums to check if they are equal
      return index;
    };
  });
};

我的理解是,如果 suma 和 sumb 不相等,则 forLoop 的下一次迭代将开始,但是这不会发生,我不明白为什么。

如果不存在这样的值,该函数应该返回 -1,我目前还没有实现这部分代码。

谢谢

标签: javascriptforeach

解决方案


您的代码有两个问题:

  1. 正如我在评论中指出的那样,在原地Array.prototype.slice改变/更改数组,当您同时迭代数组时,这是一个坏主意。因此,在拼接之前对数组进行浅拷贝,通过使用扩展运算符,即[...arr].splice()
  2. 您是从 foreach 函数返回,但不是从外部findEvenIndex()函数返回。

更好的解决方案是简单地使用for循环:一旦找到索引,我们可以使用break短路并跳出循环,因为我们不想执行进一步的分析。我们将索引存储在for 循环外的变量中,并返回它:

function findEvenIndex(arr) {
  let foundIndex = -1;
  
  for(let index = 0; index < arr.length; index++) {
    const a = [...arr].splice(index + 1, arr.length); //array of values after current value
    const b = [...arr].splice(0, index); //array of values before current value
    
    const suma = a.reduce((accumulator, currentValue) => { //Sum of array of after values
      return accumulator + currentValue;
    }, 0);
    const sumb = b.reduce((accumulator, currentValue) => { //Sum of array of before values
      return accumulator + currentValue;
    }, 0);
    
    if (suma === sumb) {  //comparing the two sums to check if they are equal
      foundIndex = index;
      break;
    };
  };
  
  return foundIndex;
};

console.log(findEvenIndex([1,2,3,4,3,2,1]));


推荐阅读