2016-08-15 185 views
0

我正在做的JavaScript项目,你做一个简单的摇滚纸剪刀游戏,我似乎无法弄清楚为什么我的代码只返回“玩家赢“即使球员应该输球。下面的代码:其他语句不工作在JavaScript(只返回如果和如果其他)

var userChoice = prompt("Do you choose rock, paper or scissors?"); 
 
console.log("Player: " + userChoice) 
 

 
var computerChoice = Math.random(); 
 
console.log(computerChoice) 
 

 
if (computerChoice < 0.34) { 
 
    computerChoice = "rock" 
 
} else if (computerChoice > 0.67) { 
 
    computerChoice = "paper" 
 
} else { 
 
    computerChoice = "scissors" 
 
} 
 
console.log("Computer: " + computerChoice); 
 

 
var compare = function(userChoice, computerChoice) { 
 
    var x = userChoice 
 
    var y = computerChoice 
 
    if (x === y) { 
 
    return "The result is a tie!" 
 
    } 
 
    if (x === "rock", y === "scissors") { 
 
    return "player wins" 
 
    } else if (x === "scissors", y === "paper") { 
 
    return "player wins" 
 
    } else if (x === "paper", y === "rock") { 
 
    return "player wins" 
 
    } else { 
 
    return "You lose" 
 
    } 
 
} 
 

 
compare(userChoice, computerChoice)

同样在一个侧面说明,为什么计算器上的控制台上时,在codeacademy控制台不显示的回报。

+0

问题是如果条件使用逻辑运算符而不是**,**。像** x === 5 || y === 3 ** –

+0

不幸的是我没有足够好的蟒蛇,看起来很有趣,虽然 –

+0

不要添加评论到您的问题。在评论部分添加评论。 – 2016-08-15 06:49:43

回答

-1

我猜你失去了一些东西,也许你应该改变:

if (x === "rock", y === "scissors") { 

if (x === "rock" && y === "scissors") { 

其他条件语句应该是这样做的上方。

1

您应该使用运营商&&而不是,

var compare = function(userChoice, computerChoice) { 
    var x = userChoice; 
    var y = computerChoice; 

    if (x === y) { 
    return "The result is a tie!"; 
    } 
    if (x === "rock" && y === "scissors") { 
    return "player wins"; 
    } else if (x === "scissors" && y === "paper") { 
    return "player wins"; 
    } else if (x === "paper" && y === "rock") { 
    return "player wins"; 
    } else { 
    return "You lose"; 
    } 
}