简体   繁体   中英

While loop with 2 conditions using || in javascript

I am in the process of going through The Odin Project. There is an assignment which has required me to create a rock, paper, and scissors game. The issue I currently have right now is with knowing when to end the game.

while (computerScore < 3 || playerScore < 3) {
let answer = prompt('Rock, Paper, or Scissors');
   console.log(playRound(answer, computerPlay()));
   console.log("Computer has " + computerScore + " points and you have " + playerScore + " points.")
     }

If you look above you see that I having a loop that keeps looping if the score of the computer or player is less than 3, but the loop only stops when both players have hit 3. I would like the loop to stop when either the computer or player has hit 3 points.

playRound is a function that will check who wins also will add 1 point to the winner score.

Any help is appreciated!

Just go on if both players have a value smaller than three by taking an logical AND && .

The loop exits if one player have a score of 3.

while (computerScore < 3 && playerScore < 3) {
    // ...
}

To expand on some of the answers that tell you HOW to fix it, I'd like to point out WHY your code isn't working.

Currently, your code states that if the player's score is less than 3 OR the computer's score is less than 3, do the while loop. Remember that the while condition will run through the loop as long as the condition evaluates to true .

So if the computer reaches a score of 3 and the player has a score of 2, your condition will currently evaluate to true because the player DOES have a value less than 3.

You need to use the && operator so that your condition evaluates to false when one of the player's scores reaches 3.

let computerScore = 3;
let playerScore = 2;

//computerScore < 3 = false;
//playerScore < 3 = true;

//while(false || true) evaluates to true
while(computerScore < 3 || playerScore < 3){
    //code will always run as long as one of the players' scores is < 3
}

//while(false && true) evaluates to false
while(computerScore < 3 && playerScore < 3){
    //code will stop running when either player's score reaches 3
}

Use && not || if you want stop loop on any of the conditions

while (computerScore < 3 && playerScore < 3) {
let answer = prompt('Rock, Paper, or Scissors');
   console.log(playRound(answer, computerPlay()));
   console.log("Computer has " + computerScore + " points and you have " + playerScore + " points.")
}

只需使用&&

(computerScore < 3 && playerScore < 3)

You are asking the game to continue if either player is below 3.

You are looking for this logic:

If player less than 3 and computer less than 3, continue.

while (player < 3 && computer < 3) { 
    //play game
}

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