「JavaScript」Math.randomで乱数を取得する

2022年3月10日

書式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Math.random() * 範囲数字
Math.random() * 範囲数字
Math.random() * 範囲数字

Math.random()を使用して、乱数を取得します。
Math.random()の戻り値は、0以上1未満の小数値が取得できますので、数値に整形して使用します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//0~9の乱数を取得
var rndA = Math.floor(Math.random() * 10);
console.log(rndA);
//1~100の乱数を取得
var rndB = Math.floor(Math.random() * 100) + 1;
console.log(rndB);
//5~25の乱数を取得
var rndC = Math.floor(Math.random() * 20) + 5;
console.log(rndC);
//0~9の乱数を取得 var rndA = Math.floor(Math.random() * 10); console.log(rndA); //1~100の乱数を取得 var rndB = Math.floor(Math.random() * 100) + 1; console.log(rndB); //5~25の乱数を取得 var rndC = Math.floor(Math.random() * 20) + 5; console.log(rndC);
//0~9の乱数を取得
var rndA = Math.floor(Math.random() * 10);
 console.log(rndA);

//1~100の乱数を取得
var rndB = Math.floor(Math.random() * 100) + 1;
 console.log(rndB);

//5~25の乱数を取得
var rndC = Math.floor(Math.random() * 20) + 5;
console.log(rndC);

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
3
33
14
3 33 14
3
33
14

 

JavaScript

Posted by arkgame