为什么这个javascript函数调用不起作用

Why is this javascript function call not working?

本文关键字:函数调用 不起作用 javascript 为什么      更新时间:2024-05-04

调用我的函数会产生语法错误,其他一切都会自行运行。错误在上引发。

console.log(compare(userChoice, computerChoice));

错误为:

SyntaxError:意外的令牌{

有什么想法吗?

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34)
{
	computerChoice = "rock";
} 
else if(computerChoice <= 0.67)
{
	computerChoice = "paper";
} 
else 
{
	computerChoice = "scissors";
}
var compare = function(choice1, choice2)
{
    if (choice1 === choice2)
    {
        return "The result is a tie!";
    }
    else if (choice1 === "rock")
    {
        if (choice2 === "scissors")
        {
            return "rock wins";
        }
        else 
        {
            return "paper wins";
        }
    }
    else if (choice1 === "paper")
    {
     
      if (choice2 === "rock")
        {
            return "paper wins"
        }
        else
        {
            return "scissors wins"
        }
        
    }
    else if (choice1 === "scissors")
    {
        if (choice2 === "paper"
        {
            return "paper wins"
        }
        else
        {
            return "scissors wins"
        }
    }
}
console.log(compare(userChoice, computerChoice));

是的,您在if (choice2 === "paper"处忘记了)

正如其他人所指出的,您的一个结束)丢失了。

使用大量嵌套的if-else块,很容易丢失对(){}的跟踪。如果您使用其他条件语句和表达式,即switch语句和?运算符:,则可以编写更短、更好、更易于阅读的代码

function compare(choice1, choice2) {
    if (choice1 === choice2) {
        return 'The result is a tie';
    }
    switch(choice1) {
        case 'rock':
            return choice2 === 'scissors' ? 'rock wins' : 'paper wins';
        case 'paper':
            return choice2 === 'rock' ? 'paper wins' : 'scissors win';
        case 'scissors':
            return choice2 === 'paper' ? 'scissors win' : 'rock wins';
    }
}

如您所见,此代码的()s和{}s要少得多。