LoginSignup
0
0

More than 3 years have passed since last update.

Math.floorとMath.randomの組み合わせで簡易抽選アプリを作ってみる

Posted at

Math.floorとMath.randomの組み合わせで簡易抽選アプリを作ってみる

新しく2つのメソッドを覚えたので、そのアウトプット用です。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
  <style>
    body{
        text-align: center;
        font-size:100px;
        background-color: aliceblue;
    }
    </style>
</head>

<body>
    <script>
        let lot = ['1等','2等','3等','4等','5等','6等'];
        let number = Math.floor(Math.random()*lot.length);


        document.write('抽選の結果、あなたは'+lot[number]+'です');
    </script>
</body>

</html>

メソッドの解説

  • Math.floor()メソッドは、小数点以下を切り捨てる。
  • Math.random()メソッドは、0以上1未満の値をランダムに返す。

コードの解説

let lot = ['1等','2等','3等','4等','5等','6等'];
let number = Math.floor(Math.random()*lot.length);

では、lotという変数に1等〜6等までの文字列を代入する。
0から1まででランダムに出た値 × lot.length(文字列の要素数を取得するので、6)から小数点以下を切り捨てた値をnumberという変数に代入する。

document.write('抽選の結果、あなたは'+lot[number]+'です');

lot[number]とすることにより、1等〜6等までの結果をランダムに表示することができる。
8852a65d14f18add93c52201246db328.png

何等かによって色分け出来ればもっと見栄えも良くなると思います(^_^;)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0