我试图定义一个函数,该函数根据虚拟伙伴的随机选择产生不同的结果。游戏是通过提交实现的。
我创建了一个数组,然后随机选择。接下来,我尝试使用多个条件实现if语句。但是它不会返回警报。
感谢您的意见。



<h1>What is your choice?</h1><br>
<form id="d1">
  <input type="radio" name="choice" value="Cooperate"> Cooperate
  <input type="radio" name="choice" value="Betray"> Betray
</form>
<button onclick="submitAnswer()">Submit Answer</button>
<script>
  function submitAnswer() {
    var selected = document.querySelector('input[type="radio"]:checked').value;
    var myArray = ['Cooperate', 'Betray'];
    var rand = myArray[Math.floor(Math.random() * myArray.length)];
    if (selected === "Cooperate" || rand === "Cooperate") {
      alert("2");
    } else if (selected === "Betray" || rand === "Cooperate") {
      alert("3");
    } else if (selected === "Cooperate" || rand === "Betray") {
      alert("0");
    } else if (selected === "Betray" || rand === "Betray") {
      alert("1");
    }
  }
</script>

最佳答案

您有一些流氓括号。在Javascript中,整个条件子句必须用方括号括起来。另外,为了防止自动提交,请将按钮的类型设置为“按钮”。尝试这个:



<h1>What is your choice?</h1><br>
<form id="d1">
  <input type="radio" name="choice" value="Cooperate"> Cooperate
  <input type="radio" name="choice" value="Betray"> Betray
</form>
<button type="button" onclick="submitAnswer()">Submit Answer</button>
<script>
  function submitAnswer() {
    var selected = document.querySelector('input[type="radio"]:checked').value;
    var myArray = ['Cooperate', 'Betray'];
    var rand = myArray[Math.floor(Math.random() * myArray.length)];
    if (selected === "Cooperate" || rand === "Cooperate") {
      alert("2");
    } else if (selected === "Betray" || rand === "Cooperate") {
      alert("3");
    } else if (selected === "Cooperate" || rand === "Betray") {
      alert("0");
    } else if (selected === "Betray" || rand === "Betray") {
      alert("1");
    }
  }
</script>

10-04 12:14