8
5

More than 3 years have passed since last update.

【JavaScript】乱数 (範囲指定)

Posted at

はじめに

勉強したことを自分のメモ代わりに残します。

乱数

JavaScriptで乱数を作るには、「Math」オブジェクトの「random()」メソッドを使用します。

js
var random = Math.random();
//生成した乱数( Math.random() )を変数randomに代入 

console.log( random );

出力結果

0.8023803655112587

Math.random()」は0〜1未満(1は入らない)までの小数による乱数を生成することができます。

乱数の範囲指定

「0 〜 10」の範囲で乱数を作るプログラムを例に作ってみます。

js
var random = Math.random() * 11;

console.log( random );

出力結果

7.51600326571613

範囲を決めた乱数を作るときには、「Math.random()」に最大値を掛けることで作る事ができます。

しかし「Math.random()」は0〜1未満(0〜0.9999・・・・)の少数を返します。
「0 〜 10」の範囲を作りたい場合、最大値の10をそのまま掛けてしまうと「0 〜 9」の範囲になってしまうというわけです。

なので、最大値に1を足して「11」を掛けることで、「0 〜 10」の範囲を設定する事ができます。

また「Math.random()」は小数点の乱数を生成するので、これを扱いやすい整数に変える必要があります。

Math.floor()

js
var random = Math.floor( Math.random() * 11 );

console.log( random );

Mathオブジェクトの「floor()」メソッドを使えばOKです!
出力結果

7

となります。

「最小値 〜 最大値」

「最小値 〜 最大値」を任意に決めて乱数の範囲を作る事ができます。

Math.random() * ( 最大値 - 最小値 ) + 最小値;

最大値と最小値を入れてあげる事で任意の範囲を指定する事ができます。

「最大値」についてですが、上記でもあったように例えば「0 〜 10」であれば、10に1を足した「11」が「最大値」であるという点に注意しましょう。

サンプルとして、「7 〜 12」の範囲で乱数を作ってみましょう。

js
var random = Math.floor( Math.random() * 6 ) + 7;
//最小値「7」と最大値から最小値を引いた「6」を使う

「7 〜 12」なので最大値に1を足した13から最小値を引いて「6」を「random」メソッドに掛けます。最後に、最小値「7」を足してあげれば、「7 〜 12」までの範囲における乱数を生成することが出来ます。

8
5
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
8
5