Nims Nims - 28 days ago 6
Javascript Question

Using the result of a for loop statement for a condition in an else if statement

My third else if statement condition should be the result of the for loop. How do I use the loop for the condition?

//If player clicks centre on first move go in corner square
if (current[4] === playerToken && this.state.stepNumber === 1) {
let move = cornerSquares[Math.floor(Math.random() * cornerSquares.length)];
drawSquare(move);
}
//If player clicks corner square on first move go in centre square
else if (this.state.stepNumber === 1) {
for (let i = 0; i < cornerSquares.length; i++){
if (current[cornerSquares[i]] === playerToken) {
drawSquare(4);
}
}
}
//If player or computer has 2 in a row, place in 3rd square to win or block
else if (/*CONDITION OF THE BELOW FOR LOOP*/) {
for (let i = 0; i < twoInRow.length; i++) {
const [a, b, c] = twoInRow[i];
if (current[a] && current[a] === current[b]) {
drawSquare(c);
}
}
}
//Place in random empty square
else {
//code to randomly place x/o in random square
}
}

Answer Source

My third else if statement condition should be the result of the for loop => Nope.

if {} else ... are evaluated at the same time, and the first which validates condition is taken. If you want conditions evaluated one after one, you have to use if {} if {} ...