0
0

More than 1 year has passed since last update.

[JavaScript] 乱数の生成方法

Posted at

JavaScriptで、乱数を使用したので乱数の生成方法を簡単にまとめておく。

乱数の生成

JavaScriptで乱数を生成する場合、MathオブジェクトのMath.random()を使用する。
Math.random()は、0.0以上1.0未満の範囲での浮動小数点数を返す。基本的な乱数生成の書き方は以下となる。

const random = Math.random();
console.log(random);    // 0.9986124832248591

ここで、JavaScriptのMath.random()は、C言語とは異なりシード値を指定しなくても実行ごとに異なる値が生成される
さらに、乱数の値の範囲指定や整数値の乱数を生成する方法についてまとめておく。

値の範囲を指定して乱数を生成

ある範囲内の値(min以上max未満)で乱数を生成したい場合は、以下のように書ける。

// min = 3, max=5 の場合
const random = Math.random()*(max - min) + min;
console.log(random);    // 4.186149518789809

整数の乱数を生成

乱数の範囲指定に加えて、生成される乱数の値が整数になるようにする場合は、Math.floor()を使用する。Math.floor()は、引数の値以下で最大の整数を返すメソッドである。これを用いて以下のように書くことができる。

// min = 5, max=30 の場合
const random = Math.floor(Math.random()*(max - min) + min);
console.log(random);    // 17
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