Javascript不等式

时间:2015-04-11 07:00:37

标签: javascript

所以我正在为#34;摇滚纸剪刀蜥蜴Spock"制作一个Javascript程序。我正在使用Math.random()。我需要使用if/else/else if's。有人可以帮助我解决不平等问题吗?我知道我现在拥有的东西不太对劲:

   var userChoice = prompt("Do you choose Rock, Paper, Scissors, Lizard or Spock?");
var computerChoice = Math.random();
if (computerChoice > 0.20) {
    computerChoice = "rock";
} else if(computerChoice < 0.40 && >=0.20) {
    computerChoice = "paper";
} else if(computerChoice <0.60 && >=0.40 {
    computerChoice = "scissors";
}else if(computerChoice <0.80 && =>0.60 {
    computerChoice = "lizard";
}else {
    computerChoice = "Spock";
}

2 个答案:

答案 0 :(得分:1)

在每个条件中都需要左操作数和右操作数。那就是:

else if(computerChoice < 0.40 && computerChoice >=0.20) {

答案 1 :(得分:1)

我不喜欢游戏,所以我不知道获胜的订单是什么。但这可以帮到你。它只是在对数字进行分配并对数字进行比较。

我做了little fiddle

var userChoice = prompt("Do you choose Rock, Paper, Scissors, Lizard or Spock?");

var test = {
    Rock: 0,
    Paper: 1,
    Scissors: 2,
    Lizard: 3,
    Spock: 4
};

userChoice = test[userChoice]; //a number from 0 - 4

var computerChoice = Math.floor(Math.random() * 5); //(gives number from 0 to 4)

if (userChoice == computerChoice) {
    alert('it\'s a tie');
} else if (userChoice > computerChoice) {
    alert('user wins');
} else {
    alert('computer wins');
}