骰子掷成一排

Dice rolls into an array

本文关键字:一排      更新时间:2024-06-03

我想知道为什么在控制台上收到消息:"未捕获引用错误:d1未定义"

我想把骰子加入一个数组。

这是我的代码:

<html>
<head>
    <script>
  var diceRolls = [];
  diceRolls.push(d1);
  if (diceRolls[diceRolls.length - 1] === d1) {
      console.log("Je hebt 5 punten gewonnen!");
  }     
function rollDice() {
           var die1 = document.getElementById("die1");
           var status = document.getElementById("status");               
           var d1 = Math.floor(Math.random()*6) +1;
           console.log("You rolled "+d1+".");

  }

  </script>
</head>
<body>
    <div id="die1" class="dice">0</div>
    <button onclick="rollDice()"> Roll the dice </button>
    <h2 id="status" style="clear:left":> </h2>
</body>

脚本的第二行试图在尚未初始化d1时将d1推送到diceRolls。您必须在脚本的其余部分之上声明rollDice(),然后调用它将值推送到diceRolls中。

我想你可能想试试这样的东西?

var diceRolls = [];
function rollDice() {
  var die1 = document.getElementById("die1");
  var status = document.getElementById("status");               
  var d1 = Math.floor(Math.random()*6) +1;
  console.log("You rolled "+d1+".");
  diceRolls.push(d1);
}
if (diceRolls[diceRolls.length - 1] === d1) {
    console.log("Je hebt 5 punten gewonnen!");
}     
diceRolls.push(d1);

当浏览器到达这条线时,d1还没有设置。我认为,如果你把它放入rollDice函数中,你就会得到你想要的。换句话说:

function rollDice() {
       var die1 = document.getElementById("die1");
       var status = document.getElementById("status");               
       var d1 = Math.floor(Math.random()*6) +1;
       console.log("You rolled "+d1+".");
       diceRolls.push(d1);
 }

编辑:AVP以大约30秒的优势击败了我,他得到了我的选票。