我'我有麻烦的语法为我的比较函数的javascript

I'm having trouble with the syntax for my compare function for javascript

本文关键字:我的 比较 函数 javascript 语法 麻烦      更新时间:2023-09-26

我附上了我今天在codeacademy犯的错误的截图。我试图创建一个比较函数,它随机选择0到1之间的一个数字(布、剪刀或石头),输入两个选项,并根据choice1与choice2的比较返回获胜者。

第一部分是注释,但它解释了最初的剪刀布石头函数是如何构建的

代码如下:

/*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!");  
if (choice1 < 0.34) 
if(choice2 ==="scissors");
    return("rock wins");
} else if(choice2 ==="paper");{
    return("paper wins");
};    
};

它告诉我在第15行(else if行)有一个意外的标记else

当我擦除else部分时,它会给我另一个语法错误,对标记if说同样的事情。我卡住了我的语法的哪一部分是关闭的,以及如何修复它。

我有一种感觉,这与if()语句之后的===;有关,无论哪种方式,这里都是比较它们的更好的方法。

function compare(a,b)
{
    if(a==b)return "draw";
    switch(a)
    {
        case "rock":return (b=="scissors"?a:b)+" wins";
        case "paper":return (b=="rock"?a:b)+" wins";
        case "scissors":return (b=="paper"?a:b)+" wins";
    }
}
console.log(compare("scissors","paper"));
function compare(choice1, choice2) {
  if (choice1 === choice2) {
    return "The result is a tie!";
  }
  if (choice1 < 0.34) {
    if (choice2 === "scissors") {
      return "rock wins";
    } else if (choice2 === "paper") {
      return "paper wins";
    }
  }
}

查看下面分号相关错误的注释

var compare = function (choice1, choice2) {
  if (choice1 === choice2) return("The result is a tie!");  
  if (choice1 < 0.34) {
    if(choice2 === "scissors") { // remove ; here
      return("rock wins");
    } else if (choice2 === "paper") { // remove ; here
      return("paper wins");
    } // remove ; here
  } // add another else => what happens when choice1 >= 0.34 (not a rock)
};
使用所需的else块,完整的函数如下所示:
var compare = function (choice1, choice2) {
  if (choice1 === choice2) return("The result is a tie!");  
  if (choice1 < 0.34) { // rock
    if(choice2 === "scissors") {
      return("rock wins");
    } else if (choice2 === "paper") {
      return("paper wins");
    }
  } else if (choice <= 0.67) { // paper
    if(choice2 === "rock") {
      return("paper wins");
    } else if (choice2 === "scissors") {
      return("scissors wins");
    }
  } else { // scissors
    if(choice2 === "paper") {
      return("scissors wins");
    } else if (choice2 === "rock") {
      return("rock wins");
    }
  }
};

编辑
这只是为了帮助您克服对分号的混淆(如果有的话)。通常,函数定义不需要在函数体末尾加上右花括号}后加上;

function compare (choice1, choice2) {
  // ...
}

相反,当给变量赋值时,语句以分号结束。

var name = "John Doe";

因此,当我们将两者结合在一起时,我们定义了一个函数,然后在需要用分号结束的赋值语句中使用它。因此,语法为:

var compare = function (choice2, choice2) {
    // ...
};