验证传递给Javascript提示方法的用户输入字符串

时间:2015-09-22 14:54:17

标签: javascript

家庭作业帮助吸血鬼警报。我正在尝试在Codecademy上的“Rock,paper,scissors”游戏中添加用户输入字符串验证功能。 Codecademy网站上的文本编辑器验证我的代码是正确的,但我没有得到预期的行为,即如果用户未能输入“摇滚”,“纸张”或“剪刀”字符串,则返回警报

我在下面的if语句中汇总了条件:

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

function validateUserChoice(userChoice) {
    if (userChoice !== "rock" || userChoice !== "paper" || userChoice !== "scissors") {
        alert("You can only select rock, paper or scissors!");
        return false;
    }
};

这是游戏的其余部分。当调用前面的函数时,似乎旁边的比较函数被绕过,并且用户键入提示的任何字符串都被打印到屏幕上(参见底部的console.log("User Choice: " + userChoice);)。否则,当上面的函数被注释掉时,游戏会返回预期的行为:

var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
};

var compare = function(userChoice, computerChoice) {
    if (userChoice === computerChoice) {
        return "The result is a tie!";
    };

    if (userChoice === "paper") {
        if (computerChoice === "rock") {
            return "paper wins";
        } else {
            if (computerChoice === "scissors") {
                return "scissors wins";
            }
        }   
    };

    if (userChoice === "scissors") {
        if (computerChoice === "rock") {
            return "rock wins";
        } else {
            if (computerChoice === "paper") {
                return "scissors wins";
            }
        }
    }
};
console.log("User Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
compare(userChoice, computerChoice);

1 个答案:

答案 0 :(得分:3)

尝试更改以下条件,

function validateUserChoice(userChoice) {
    if (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors") {
        alert("You can only select rock, paper or scissors!");
        return false;
    }
};