如果userChoice爲空或除岩石,紙張或剪刀之外的單詞,我該如何停止執行此功能。 我試圖使用返回,但我無法讓它工作。 任何幫助表示讚賞。 感謝從Javascript中退出函數。簡單的搖滾,紙,剪刀遊戲
JS小提琴鏈接= http://jsfiddle.net/Renay/d9bea2ra/1/
var userChoice = prompt('Do you choose rock, paper or scissors?');
var compChoice = Math.random();
if (compChoice <= 0.34) {
compChoice = 'rock';
} else if (compChoice <= 0.67) {
compChoice = 'paper';
} else {
compChoice = 'scissors';
}
function compare() {
if (userChoice == compChoice) {
console.log('The result is a tie!');
} else if ((userChoice == 'rock' && compChoice == 'scissors') || (userChoice == 'paper' && compChoice == 'rock') || (userChoice == 'scissors' && compChoice == 'paper')) {
console.log('You win!');
} else {
console.log('You lose!');
}
if (userChoice === null) {
console.log('Please select an option');
} else if (userChoice !== 'rock'&&'paper'&&'scissors') {
console.log('Please select rock, paper or scissors');
}
}
console.log('Your choice = ' + userChoice);
console.log('Computer Choice = ' + compChoice);
compare();
你想在哪裏退出該功能? 'return'應該可以工作。 – Scimonster 2014-10-12 09:37:27
在if語句中,userChoice === null以及userChoice!=='rock'&&'paper'&&'scissors' – Renay 2014-10-12 09:40:11