在条件中使用逻辑和比较运算符(javascript)

时间:2015-12-29 18:36:16

标签: javascript comparison conditional logical-operators comparison-operators

我希望用户在以下代码行中的石头剪刀游戏中输入他的答案。

 <?php
$pdo = new PDO('mysql:dbname=something;host=127.0.0.1;port=3306','user','password');

$stmt = $pdo->prepare('
        UPDATE users
        SET newdatecolumn =
        STR_TO_DATE(SUBSTRING_INDEX(REPLACE(lastlogin,char(160),\' \'),\'C\',1), \'%b %d %Y, %T\');
        SELECT * FROM users
        WHERE DATEDIFF(DAY,\'2015-12-26 00:59:34\', newdatecolumn) <= 3;
        ');

$stmt->execute();

// it allow you to retrieve the data from the second statement
$stmt->nextRowset();

while($user = $stmt->fetch())
{
    // do something
}

unset($stmt);
unset($pdo);

但是,如果用户写的不仅仅是“摇滚”,“纸”或“剪刀”,他应该再次选择,我试图用这段代码做:

userChoice = prompt("Do you choose rock, paper or scissors?");

我遇到的问题是程序会将给定的输入识别为无效,即使它是“摇滚”,“纸”或“剪刀”。

在键入此内容时,我设法找到了自己的解决方案。

while (userChoice !== "rock" || "paper" || "scissors") {
    userChoice = prompt("Invalid choice. Please change your answer.");
};

这种方式确实有意义且第一个条件可能不起作用,因为即使您键入正确的答案(例如“纸张”),它仍然不等于其他两个答案(在这种情况下“摇滚“和”剪刀“),这就是为什么程序一直说答案是无效的,对吧?或者是语法错误? 现在(有了工作条件),用户的选择既不是“摇滚”,也不是“纸”,也不是“剪刀”,因此它可以正常工作。

此外,是否有可能更简单,更短的方式来编写这种情况?

注意:我希望解决方案的部分内容已经包含在内,因为它们可以帮助其他程序员。

3 个答案:

答案 0 :(得分:1)

使用indexOf

while (["rock", "paper", "scissors"].indexOf(userChoice) > -1) {

您的第一次尝试

while (userChoice !== "rock" || "paper" || "scissors") {

在技术上是一个无限循环,因为

|| "paper" 
例如,

技术上评估为true或 truthy

答案 1 :(得分:1)

两个例子

一个有数组且Array.prototype.indexOf()

var userChoice;
while (!~['rock', 'paper', 'scissors'].indexOf(userChoice)) {
    userChoice = prompt("Invalid choice. Please change your answer.");
};

另一个有一个对象和in运算符:

  

如果指定的属性位于指定的对象中, in运算符将返回true

var userChoice;
while (!(userChoice in {rock: 1, paper: 1, scissors: 1})) {
    userChoice = prompt("Invalid choice. Please change your answer.");
};

答案 2 :(得分:0)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Rock Papper Scissors Game</title>
    </head>
    <body>
        <h1>Play Rock Papper Scissors?</h1>
        <button id="start">Play?</button>
        <script> 
            function rpsGame() {
                var computerChoice = Math.random(),
                    userChoice = prompt('Do you choose rock, paper, or scissors');
                function getComputerChoice() {
                    if (computerChoice <= 0.33) {
                        computerChoice = 'rock';
                    } else if (computerChoice <= 0.66 && computerChoice >= 0.33) {
                        computerChoice = 'paper';
                    } else {
                        computerChoice = 'scissors';
                    }
                }
                function playAgain() {
                    var restart = prompt('Would you like to play again, yes or no?').toLowerCase();
                    switch(restart) {
                    case 'yes':
                        rpsGame();
                        break;
                    default:
                        alert('Okay, see you later!');
                    }
                }
                function compare() {
                    var choice1 = userChoice.toLowerCase(),
                        choice2 = computerChoice,
                        tie = "The computer chose " + choice2 + ", and you chose " + choice1 + ". The result is a tie!",
                        win = "The computer chose " + choice2 + ", and you chose " + choice1 + ". You win!",
                        lose = "The computer chose " + choice2 + ", and you chose " + choice1 + ". The computer wins!";

                    switch (choice1) {
                    case "":
                        alert("You didn't enter anything. Maybe we can play later!");
                        break;
                    case 'rock':
                        if (choice2 === 'scissors') {
                            alert(win);
                        } else if (choice2 === 'rock') {
                            alert(tie);
                        } else {
                            alert(lose);
                        }
                        playAgain();
                        break;
                    case 'paper':
                        if (choice2 === 'rock') {
                            alert(win);
                        } else if (choice2 === 'paper') {
                            alert(tie);
                        } else {
                            alert(lose);
                        }
                        playAgain();
                        break;
                    case 'scissors':
                        if (choice2 === 'paper') {
                            alert(win);
                        } else if (choice2 === 'scissors') {
                            alert(tie);
                        } else {
                            alert(lose);
                        }
                        playAgain();
                        break;
                    default:
                        alert(choice1.substring(0,1).toUpperCase() + choice1.substring(1, choice1.length).toLowerCase() + " is an invalid choice. Please change your answer.");
                        rpsGame();
                    }
                }
                getComputerChoice();
                compare();
            }
            document.getElementById('start').addEventListener('click', rpsGame);
        </script>
    </body>
</html>