javascript - If 语句中预期的声明或语句
问题描述
所以我正在编写一些代码来用 Javascript 构建一个简单的应用程序,其中计算机有一个随机数分配给石头、纸、剪刀,然后随机选择,然后还有一个用户选择。代码没有运行不知道为什么。
我尝试在determineWinner 函数的主if 语句内的if 语句末尾添加分号。
const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors'){
return userInput;
}else {
console.log('Error, you must type rock, paper, or scissors');
}
}
function getComputerChoice(){
var randomNumber = Math.floor(Math.random() * 3);
switch (randomNumber) {
case 0:
return 'rock';
case 1:
return 'paper';
case 2:
return 'scissors';
}
}
function determineWinner(userChoice, computerChoice){
if(userChoice === computerChoice){
return 'This game is a tie!'
} else if(userChoice === 'rock'){
if(computerChoice === 'paper'){
return 'The computer has won!';
}else{
return 'The user has won';
}
} else if(userChoice === 'paper'){
if(computerChoice === 'scissors'){
return 'The computer has won!';
}else(computerChoice === 'rock');{
return 'The user has won!';
}
}else(userChoice === 'scissors');{
if(computerChoice === 'rock'){
return 'The computer has won!';
}else(computerChoice === 'paper');{
return 'The user has won!';
}
}
}
}
console.log(determineWinner('paper', 'scissors'));
在脚本末尾运行 console.log 时,它应该显示计算机已获胜。
解决方案
由于您所有的if
案例都只是返回,因此您不需要使用else
,因为 if-case 将始终返回。像这样:
function determineWinner(userChoice, computerChoice){
if (userChoice === computerChoice) {
return 'This game is a tie!'
}
if (userChoice === 'rock') {
if(computerChoice === 'paper') {
return 'The computer has won!';
}
return 'The user has won';
}
if (userChoice === 'paper') {
if(computerChoice === 'scissors'){
return 'The computer has won!';
}
return 'The user has won!';
}
if (userChoice === 'scissors') {
if(computerChoice === 'rock') {
return 'The computer has won!';
}
return 'The user has won!';
}
}
另一种方法是在函数末尾返回,答案如下:
function determineWinner(userChoice, computerChoice){
const results = [
'This game is a tie!',
'The computer has won!',
'The user has won!'
];
let winner;
if (userChoice === computerChoice) winner = 0;
else if (userChoice === 'rock') {
winner = computerChoice === 'paper' ? 1 : 2;
}
else if (userChoice === 'paper') {
winner = computerChoice === 'scissors' ? 1 : 2;
}
else if (userChoice === 'scissors') {
winner = computerChoice === 'rock' ? 1 : 2;
}
return results[winner];
}
推荐阅读
- android - 在 Fragment 中,单击 listView 项以打开新活动并将值传递给其他活动
- javascript - 如何在 Firestore 中订购文档?
- android - Google 登录 - 关闭登录对话框时出现 ApiException 12501
- ios - iOS:在 touchesEnded 完成后删除数组中的最后一个图像
- c# - 删除和克隆存储库后丢失 nuget 引用
- excel - 需要相对于今天的日期计算 Excel 中的某些文本,每个单元格中都有大量可变数据
- makefile - gnu make:为什么叫“顶级”目标?
- virtual-machine - Genymotion 启动失败(vrc=VERR_SUPDRV_COMPONENT_NOT_FOUND,rc=E_FAIL (0X80004005))
- linux - 避免在 bash 中使用数组进行通配符扩展
- c# - C# 多部分响应构建