【问题标题】:Use of logical and comparison operators in conditions (javascript)在条件中使用逻辑和比较运算符(javascript)
【发布时间】:2015-12-29 18:36:16
【问题描述】:

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

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

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

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

我遇到的问题是程序一直将给定的输入识别为无效,即使它是“石头”、“纸”或“剪刀”。


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

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

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

另外,是否有一种更简单、更简短的方式来编写该条件?

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

【问题讨论】:

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


    【解决方案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.");
    };

    【讨论】:

    • 很好地使用in!而且我不知道您的第一个示例中的~ 是什么。 (去寻找它)。喜欢我从别人那里学到新东西的答案:-)
    • 嘿,对于那些对~ 所做的事情感兴趣的人:stackoverflow.com/questions/12299665/…
    【解决方案2】:

    使用indexOf

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

    你的第一次尝试

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

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

    || "paper" 
    

    例如,在技术上评估为 true 或 truthy

    【讨论】:

    • 很好的解决方案,谢谢。另外,感谢您指出其他情况出了什么问题。 :)
    • @Maurice,没问题。很高兴答案有帮助:-)
    【解决方案3】:
    <!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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 2015-07-03
      • 1970-01-01
      • 2016-11-20
      相关资源
      最近更新 更多