2016-08-15 198 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"; 
    } 
}