【JavaScript】Math.randomメソッドとは?乱数を使いこなそう!
Math.randomメソッドとは
Math.random()とは、JavaScriptで乱数を取得するメソッドです。このメソッドの特徴は、「0以上1未満の実数をランダムで返す」ことです。そのため乱数を整数で取得したり、指定の範囲の乱数を取得したい場合は少し工夫する必要があります。
それではMath.random()の構文と例を見ていきましょう。
Math.random():構文
1.Math.random() // 返り値: 0以上1未満のランダムな実数
引数は必要なく、これだけで乱数を取得できます。
Math.random():サンプルプログラム
- randSample.js
- 実行結果
1.2.3.for (let i = 0; i < 3; i++) { console.log(Math.random()); }
1.2.3.0.591352161068941 0.940308167233467 0.8954125619131694
このように、メソッドを呼び出す度に値が変わっていることが分かりますね!
次はこの乱数をもっと使いやすくしていきます。
乱数の範囲を指定しよう
乱数の取得は簡単にできることが分かりましたが、0以上1未満の実数そのままでは少し使いにくい場合があります。
例えば、5人の中から奢る人を等確率で決めたいときはどうでしょうか?Math.random()をそのまま使えば、if文で乱数の範囲を元に条件分岐することで実現できそうです。しかし、5人を配列に入れて、0~4の乱数(整数)を取得できればめっちゃ楽じゃないですか?
Math.random():男気ルーレット
- treat1.js
- treat2.js
- 実行結果(共通)
1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.function getRandomPerson() { let index; const people = ['Mary', 'Tom', 'Nick', 'Jeny', 'Watson']; const len = people.length; const rand = Math.random(); // randを元に等確率でindexを作成 if (rand < 1 / len) index = 0; else if (rand < 2 / len) index = 1; else if (rand < 3 / len) index = 2; else if (rand < 4 / len) index = 3; else index = 4; return people[index]; } console.log(`It's on ${getRandomPerson()}!`);
1.2.3.4.5.6.7.8.9.function getRandomPerson() { const people = ['Mary', 'Tom', 'Nick', 'Jeny', 'Watson']; const len = people.length; const index = getRandomInt(0, len - 1); // 0以上len-1以下のランダムな整数を取得(後で作成) return people[index]; } console.log(`It's on ${getRandomPerson()}!`);
1.It's on Nick!
このように、乱数を整数で取得したり、範囲を変えたりできるとプログラムの作成が一気に楽になることがあります。
それでは実際にオリジナルの関数を作ってみましょう。(コピペOKです!)
min以上max未満の乱数
まずは「最小値min以上, 最大値max未満」の乱数(実数)を取得してみます。
min以上max未満の乱数(実数)
- getRandom.js
- 実行結果
1.2.3.4.5.6.7.8.// min以上max未満の乱数(実数)を返す function getRandom(min, max) { const rand = Math.random() * (max - min) + min; return rand; } console.log(getRandom(2, 7.5)); console.log(getRandom(-10, -2.5));
1.2.6.355970888942062 -9.823054228785013
これで指定の範囲の乱数を実数で得ることができました。今後はgetRandom関数を呼ぶだけでOKですね!
min以上max以下の乱数(整数ver.)
次に「最小値min以上, 最大値max以下」の乱数(整数)を取得してみます。(maxを含みます。)
min以上max以下の乱数(整数)
- getRandomInt.js
- 実行結果
1.2.3.4.5.6.7.8.9.10.// min以上max以下の乱数(整数)を返す function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); const rand = Math.floor(Math.random() * (max - min + 1) + min); return rand; } console.log(getRandomInt(1, 10)); console.log(getRandomInt(-9.5, -2.5));
1.2.8 -9
先ほどのgetRandom関数とあまり変わりませんが、得られた乱数を整数にするためMath.floorメソッドを使用して小数点以下を切り捨てています。ちなみに、3, 4行目でminとmaxを整数に丸めているのは、引数min, maxに実数を入れて関数を呼んだ際に得たい乱数の範囲を超えないようにするためです。
ちなみに、5行目の+1を無くすとmin以上max未満の範囲になります。
Math.floor()についてはこちら ↓
おまけ:ガチャガチャプログラム
最後におまけとして、乱数を使ったプログラムの定番、ガチャガチャを作ってみました。詳しい解説はしませんが、コメントを参照しながら見てみて下さい!
ガチャガチャ
- index.html
- gacha.js
1.2.3.4.5.6.7.8.9.10.11.12.13.14.<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>ガチャガチャ</title> </head> <body> <h1>ガチャガチャ</h1> <button id="btn">ガチャを引く</button> <div id="result"></div> <script src="./gacha.js"></script> </body> </html>
1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.31.32.33.34.// min以上max以下の乱数(整数)を返す function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); const rand = Math.floor(Math.random() * (max - min + 1) + min); return rand; } function gacha() { const items = { rare5: ['メロン', 'マンゴー'], rare4: ['イチゴ', 'もも', 'スイカ'], rare3: ['ぶどう', 'みかん', 'バナナ', 'リンゴ'] }; let target; const rareRand = getRandomInt(1, 100); // 1 ~ 100までの乱数を取得 // どのレア度のアイテムが出るかを決め、targetにリストを入れる。 if (1 <= rareRand && rareRand <= 10) { target = items.rare5; // 10%の確率で星5 } else if (11 <= rareRand && rareRand <= 40) { target = items.rare4; // 30%の確率で星4 } else { target = items.rare3; // 60%の確率で星3 } // 得られたレア度のリストから、等確率でアイテムを決める。 const itemRand = getRandomInt(0, target.length - 1); // target.length ... 配列の要素数 const item = target[itemRand]; document.getElementById('result').textContent = `${item}をゲット!`; } document.getElementById('btn').addEventListener('click', gacha);
デザインは最悪ですが、よくあるゲームのガチャの機能だけならこれだけで作れてしまいます!興味がある人はCSSでデザインを整えてみると、もう立派なゲームです!
まとめ
今回はJavaScriptで乱数を扱う方法について解説しました。動きにランダム性を持たせたい場合は重宝するので、ぜひ覚えてみて下さい!
それではまた次回~。