簡體   English   中英

如何擺脫這個楠?

[英]How to get Rid of this Nan?

我正在構建一個只有 Html 和 Javascript 的骰子。 我想要兩個隨機生成的數字(相加)的結果。 我怎樣才能得到結果作為兩個數字的總和。

<!DOCTYPE html>
<html>
<head>
    <title>Dice</title>
    <h1 style="text-align:center;color:lime;font-size:300%">Dice</h1>
    <hr/>
    <br/>
    <h1 style="color: red;text-align:center;font-size:250%">You Have Got:</h1>
    <h1 style="color:gold;text-align:center;font-size:300%"><script type="text/javascript">
        var num1 = document.write(Math.floor(Math.random() * 6 + 1));
        
        document.write("<br/>");
        document.write("<br/>");

        var nu,2 = document.write(Math.floor(Math.random() * 6 + 1));
        
        document.write("<br/>");

        num1 = parseFloat(num1);
        num2 = parseFloat(num2
);
  
        document.write("<br/>");

        document.write("Result:");

        document.write(dice1 + dice2);
     </script></h1>
    <button onClick="window.location.reload();" style="font-size:200%; margin:auto;display:block;background-color:black;color:cyan">Roll Again</button>
</head>
<body style="background-color:black">
</body>
</html>

所以如果我運行這個程序。 我得到的結果為 NaN。 我試過了

parseInt();
parseFloat();   

這是屏幕截圖

我只會將數字存儲為單獨的變量,因此您不必在添加之前進行轉換。

<!DOCTYPE html>
<html>

<head>
  <title>Dice</title>
  <h1 style="text-align:center;color:lime;font-size:300%">Dice</h1>
  <hr />
  <br />
  <h1 style="color: red;text-align:center;font-size:250%">You Have Got:</h1>
  <h1 style="color:gold;text-align:center;font-size:300%">
    <script type="text/javascript">

      var num1 = Math.floor(Math.random() * 6 + 1);
      document.write(num1);

      document.write("<br/>");
      document.write("<br/>");

      var num2 = Math.floor(Math.random() * 6 + 1);
      document.write(num2);

      document.write("<br/>");

      //num1 = parseFloat(num1);
      //num2 = parseFloat(num2);

      document.write("<br/>");

      document.write("Result:");

      document.write(num1 + num2);
    </script>
  </h1>
  <button onClick="window.location.reload();"
    style="font-size:200%; margin:auto;display:block;background-color:black;color:cyan">Roll Again</button>
</head>

<body style="background-color:black">
</body>

</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM