在else if语句中使用for循环语句的结果

时间:2017-08-28 08:16:38

标签: javascript loops if-statement

我的第三个if语句条件应该是for循环的结果。我如何使用循环的条件?

{{1}}

3 个答案:

答案 0 :(得分:1)

如果您可以像这样定义c,那么您可以将循环带到一个单独的函数,如下所示:

    let c = null;
    //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

    //in JS you can assign inside of an 'if' statement
    //an assignment evaluates to the value assigned
    //so we assign the result of 'hasTwoInRow' to 'c' and check if it's not null
    else if ((c = hasTwoInRow(twoInRow,current)) !== null) {
      drawSquare(c);
    }
    //Place in random empty square
    else {
     //code to randomly place x/o in random square
    }
  }

  function hasTwoInRow(twoInRow,current) {
    for (let i = 0; i < twoInRow.length; i++) {
      const [a, b, c] = twoInRow[i];  
      if (current[a] && current[a] === current[b]) {
        return c;
      }
    return null;
  }

答案 1 :(得分:1)

您可以使用move变量来指示您发现移动的位置,并在下一个if(不使用else)中使用该移动:

let move = null;
//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)];
} 
//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) {
            move = 4;
            break; // Don't lose time on looping further
        }
    }
}
//If player or computer has 2 in a row, place in 3rd square to win or block
if (move === null) {
    for (let i = 0; i < twoInRow.length; i++) {
        const [a, b, c] = twoInRow[i];  
        if (current[a] && current[a] === current[b]) {
            move = c;
            break; // Don't lose time on looping further
        }
    }
}
//Place in random empty square
if (move === null {
    //code to randomly place x/o in random square
    move = // your logic here
}
// Perform move
drawSquare(move);

答案 2 :(得分:0)

My third else if statement condition should be the result of the for loop =&gt;不。

if {} else ...同时进行评估,并且第一个验证条件。如果您想要一个接一个地评估条件,则必须使用if {} if {} ...