JavaScriptで乱数を表示する方法
JavaScriptで乱数を表示する方法
乱数を発生させる場合、Math.random()を使用する。
・0~1の乱数を取得する
var rand = Math.random();
・0~9の乱数を取得する
var rand = Math.floor(Math.random() * 10);
・1~100の乱数を取得する
var rand = Math.floor(Math.random() * 100) + 1;
・5~15の乱数を取得する
var rand = Math.floor(Math.random() * 11) + 5;
(Math.floor()で小数点以下を切り捨て)
(使用例)
1~10のランダムな数字が表示されるプログラム
<html> <head> <title>title</title> </head> <body> <script type="text/javascript"> <!-- var rand = Math.floor(Math.random() * 10) + 1; //乱数を発生 document.write(rand);//値を表示 // --> </script> </body> </html>
まとめ
・乱数を発生させるには、Math.random()を使う
・記述を変えることで乱数の範囲を変えることができる
・Math.floor()を使うことで、小数点以下を切り捨てることができる
読まれている記事
htmlst.hatenablog.jp
htmlst.hatenablog.jp