【问题标题】:Dice rolls into an array骰子滚成一个数组
【发布时间】:2013-12-11 06:00:38
【问题描述】:

我想知道为什么我在控制台收到消息:'Uncaught ReferenceError: d1 is not defined'

我想将掷骰子添加到数组中。

这是我的代码:

<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 后定义它。

标签: javascript arrays dice


【解决方案1】:

当你还没有初始化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!");
}     

【讨论】:

    【解决方案2】:
    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 秒的优势击败了我,他得到了我的投票。

    【讨论】:

      猜你喜欢
      • 2018-09-24
      • 2014-03-16
      • 2013-09-17
      • 1970-01-01
      • 2021-06-25
      • 2016-08-10
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      相关资源
      最近更新 更多