简体   繁体   中英

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".

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.

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)

See the following code, to see how let/var result in different outputs

 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM