Javascript TIPS No.8 乱数を作る「Math.random()*数値」

  • 「Math.random()」を使って、0〜99までのランダムな数字を作ってみます。
  • 例によって、Javascriptは0から順番に数えて行くので、間違わないように!

サンプルコード

<html lang="ja-JP">
<title>乱数を作る</title>
<script type=text/javascript>

document.write(Math.random()*100);

</script>
</head>
<body>

</body>
</html>

サンプルを見る

乱数が取得できました。
しかし、これだけでは邪魔な小数点がひっついてしまい、欲しい値が取得できません

  • 上のサンプルで作った乱数から、さらに整数のみを取り出して表示しています。
  • Mathが2重になっていますが、問題ありません。

サンプルコード

<html lang="ja-JP">
<title>乱数を作る</title>
<script type=text/javascript>

document.write(Math.floor(Math.random()*100));

</script>
</head>
<body>

</body>
</html>

サンプルを見る