为什么在运行代码时会发生这种情况

时间:2017-01-11 04:44:18

标签: javascript if-statement

嘿伙计,只是当我运行这段代码时,我收到三条警告,说“你赢了!”,“这是一个平局!”并且“你输了”,只应该有一个警报。这是一个石头剪刀游戏代码的哪一部分错了我试过但找不到它

{{1}}

3 个答案:

答案 0 :(得分:2)

如果您正确使用===检查d的值,则表示您使用=代替===来检查userAnswer的值。

=在左侧的变量权上指定值

===比较运算符(检查操作数的typevalue

使用===进行检查。例如:userAnswer === "Rock"

var userAnswer = prompt("Rock, Paper or Scissor");

var theEnemy;
var d = Math.floor(Math.random() * 10 + 1);

document.write(d);


if (d === 3 || d === 2 || d === 1) {
  var theEnemy = "Paper"
  if (userAnswer === "Rock") {
    alert("You lost!");
  }
  if (userAnswer === "Paper") {
    alert("it's a tie!");
  }
  if (userAnswer === "Scissor") {
    alert("You won");
  }
}

if (d === 7 || d === 6 || d === 5 || d === 4) {
  var theEnemy = "Rock";
  if (userAnswer === "Rock") {
    alert("it's a tie!");
  }
  if (userAnswer === "Paper") {
    alert("YOu won!");
  }
  if (userAnswer === "Scissor") {
    alert("You lost!");
  }
}

if (d === 8 || d === 9 || d === 10) {
  var theEnemy = "Scissor";
  if (userAnswer === "Rock") {
    alert("You lost!");
  }
  if (userAnswer === "Paper") {
    alert("You won!");
  }
  if (userAnswer === "Scissor") {
    alert("It's a tie");
  }
}

答案 1 :(得分:2)

您不是在检查,而是分配值

if(d === 3 || d === 2 || d === 1){
 var theEnemy = "Paper"
    if(userAnswer == "Rock"){
    alert("You lost!");
    }
    if(userAnswer == "Paper"){
    alert("it's a tie!");
    }
    if(userAnswer == "Scissor"){
    alert("You won");
    }
}

答案 2 :(得分:1)

如果您应该使用==

检查条件,则单个等于分配
 var userAnswer = prompt("Rock, Paper or Scissor");
 var theEnemy;
 var d = Math.floor(Math.random() * 10 + 1);
 document.write(d);
 if (d === 3 || d === 2 || d === 1) {
 var theEnemy = "Paper"
 if (userAnswer == "Rock") {
     alert("You lost!");
 }
 if (userAnswer == "Paper") {
     alert("it's a tie!");
 }
 if (userAnswer == "Scissor") {
     alert("You won");
 }
   }
if (d === 7 || d === 6 || d === 5 || d === 4) {
 var theEnemy = "Rock";
 if (userAnswer == "Rock") {
     alert("it's a tie!");
 }
 if (userAnswer == "Paper") {
     alert("YOu won!");
 }
 if (userAnswer == "Scissor") {
     alert("You lost!");
 }
}
 if (d === 8 || d === 9 || d === 10) {
 var theEnemy = "Scissor";
 if (userAnswer == "Rock") {
     alert("You lost!");
 }
 if (userAnswer == "Paper") {
     alert("You won!");
 }
 if (userAnswer == "Scissor") {
     alert("It's a tie");
 }
 }