LoginSignup
43
40

More than 5 years have passed since last update.

いまさらですが JavascriptでMath.random()

Posted at

動作確認環境

Chrome バージョン70.0.3538.67

Math.random()

Javascriptでランダムな値を得たい場合、Math.random()を使うことができます。
Math.random()は0以上、1未満の値を返します。

console.log(Math.random());
// 0.8369887702642478
// 0以上、1未満

この値を用いて計算処理をすることで、用途に合わせた数値を得ることができます。

0以上10未満の数値の中から1つ数値を選ぶ

var num = Math.floor(Math.random() * 10);
console.log(num);
// 0~9の数値の中のどれか

Math.random()の結果に数値を掛け合わせ、Math.floor()で小数点以下を切り捨てることで目的の数値を得ることができます。
Math.random()が0以上、1未満の数値を返すため(1は返らない)、10をかけても10になることはありません。
そのため、10を含んだ数値の中から値を得たいときは11をかける必要があります。(次の例)

0以上10以下の数値の中から1つ数値を選ぶ

var num = Math.floor(Math.random() * 11);
console.log(num);
// 0~10の数値の中のどれか

1以上10以下の数値の中から1つ数値を選ぶ

var num = 1 + Math.floor(Math.random() * 10);
console.log(num);
// 1~10の数値の中のどれか

Math.floor(Math.random() * 10)によって0~9の値が返るため、1を足すことで1~10の間のどれかになります。

43
40
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
43
40