[英]Why does my loop not stop, even though it's at the end?
So, I have an array and I wanted to check if some values are the same or 0. And if not, than it should call the function "end" and stop, but instead it never stops and keeps calling the function "end".所以,我有一个数组,我想检查一些值是否相同或 0。如果不是,它应该调用 function “结束”并停止,但它永远不会停止并继续调用 function “结束”。
function test() {
loop:
for (var x = 0; x < arr.length; x++) {
if (arr[x] === 0) break;
else if (x + 1 === arr.length) {
for (var x = 0; x < 4; x++) {
for (var y = 0; y < 3; y++) {
if (arr[4 + x + y * 4] === arr[x + y * 4]) break loop;
if (arr[11 - x - y * 4] === arr[15 - x - y * 4]) break loop;
}
}
for (var y = 0; y < 4; y++) {
for (var x = 0; x < 3; x++) {
if (arr[1 + x + y * 4] === arr[x + y * 4]) break loop;
if (arr[14 - x - y * 4] === arr[15 - x - y * 4]) break loop;
}
}
end();
}
}
}
Edit: found the problem, I used the x variable twice.编辑:发现问题,我使用了 x 变量两次。
Sorry for wasting your time抱歉浪费您的时间
Could you show matriz data?你能显示矩阵数据吗? And explain better what is the requeriment of your problem?
并更好地解释您的问题的要求是什么? Maybe we could find alternatives or apply other logic.
也许我们可以找到替代方案或应用其他逻辑。
for starters: declare loop iteration variables with let instead of var - variables declared with var are scoped to the function (while let/const are scoped to the code block/loop)对于初学者:用 let 而不是 var 声明循环迭代变量 - 用 var 声明的变量的范围为 function(而 let/const 的范围为代码块/循环)
See the following code, to see how let/var result in different outputs请参阅以下代码,了解 let/var 如何导致不同的输出
for (var x = 0; x < 3; x++) { console.log("outer loop var" + x) for (var x = 0; x < 2; x++) { console.log("inner loop var" + x) } } for (let x = 0; x < 3; x++) { console.log("outer loop let" + x) for (let x = 0; x < 2; x++) { console.log("inner loop let" + x) } }
in the loops with var both loops use the same variable - so the loop is exited after only 1 iteration of the outer loop (+ 2 of the inner one) (since x reaches 3 because both the inner and outer loop use the same variable to iterate - and therefor also add to the same variable after each iteration - so the inner loop is exited, because x reaches 2, then the first iteration of the outer loop ends and 1 is added, which means x becomes 3 and the loop is exited)在带有 var 的循环中,两个循环都使用相同的变量-因此仅在外部循环的 1 次迭代(内部循环的 + 2 次)后退出循环(因为 x 达到 3,因为内部和外部循环都使用相同的变量迭代 - 因此在每次迭代后也添加到相同的变量 - 所以退出内部循环,因为 x 达到 2,然后外部循环的第一次迭代结束并添加 1,这意味着 x 变为 3 并退出循环)
int the loops with let both loops each use their own variable, so we get our intended 3 iterations of the outer loop and 3 * 2 for our inner loop. int 循环让两个循环都使用自己的变量,所以我们得到了我们预期的外循环的 3 次迭代和我们的内循环的 3 * 2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.