Home > OS >  Why does my loop not stop, even though it's at the end?
Why does my loop not stop, even though it's at the end?

Time:07-26

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

CodePudding user response:

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)
  }
}

CodePudding user response:

Could you show matriz data? And explain better what is the requeriment of your problem? Maybe we could find alternatives or apply other logic.

  • Related