为什么这个比较函数返回错误的结果?

时间:2014-09-16 23:55:19

标签: javascript

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";
        }
   }
}
};

我哪里错了?

2 个答案:

答案 0 :(得分:3)

您刚刚错误地嵌套if,请执行以下操作:

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";
    }
  }
};

答案 1 :(得分:-2)

你需要在return和值之间加一个空格。

return "The result is a tie!";代替return"The result is a tie!";

请查看http://jslint.com/语法错误。