Home > Software engineering >  Variable's value changes for no reason
Variable's value changes for no reason

Time:06-20

I am trying to make a simple tiktakto game with html, css, js. I am making a gamemode where you can square up against the computer. This code is supposed to check if a column should be blocked by the bot:

for(let i = 0; i <= 2; i  )
    {   
        for(j = 0; j <= 2; j  )
        {
            console.log("j = ", j)
             
            S  = board[j][i];
        }  // <-- inside for loop j only goes from 0 to 2

        if(S === 2) // <-- inside of this if statemnt j is 3
        {   
            console.log("j = ", j) 
            if(prevent(i, j, "column")) return 1;
            else return 0;
        }
        S = 0;
    }

However somewhere after for loop the value of j randomly goes from 2 to 3 before the prevent() function can be executed, why?

CodePudding user response:

This for loop:

for (j = 0; j <= 2; j  ) {
  console.log("j = ", j)

  S  = board[j][i];
}

Is equivalent to this while loop:

j = 0
while (j <= 2) {
  console.log("j = ", j)

  S  = board[j][i];

  j  
}

So if j <= 2 is true the body loop body is executed and also the j .

CodePudding user response:

The for loop will only stop once the condition evaluates to false. Here, the first time j <= 2 is false is when j has been incremented to 3.

  • Related