javascript - 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,我目前还没有实现这部分代码。
谢谢
解决方案
您的代码有两个问题:
- 正如我在评论中指出的那样,在原地
Array.prototype.slice
改变/更改数组,当您同时迭代数组时,这是一个坏主意。因此,在拼接之前对数组进行浅拷贝,通过使用扩展运算符,即[...arr].splice()
- 您是从 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]));
推荐阅读
- git - 源树 - 如何恢复推送的提交
- php - SYmfony - 403 - 禁止:访问被拒绝。或者将应用程序代码上传到新服务器时只是空白页
- bash - 在意外标记“fi”附近出现语法错误
- python - python django长轮询等待
- python - CircleCI 和 Config.yml 的问题没有找到 requirements.txt 和 dev_requirements.txt
- discord.js - discord.js 类似门票的机器人错误 - 'TypeError: fn.bind is not a function'
- java - 在groovy(java)中如何自动找出json字段类型并从json返回值,用空格替换null?
- c# - UseSqlServer 中的连接字符串
- javascript - 分页和表单验证
- r - 将“y 确认”确认对话框添加到 R 函数?