どうも、ちょげ(@chogetarou)です。
整数の乱数を特定の範囲で生成する方法を紹介します。
方法

整数の乱数を特定の範囲で生成するには、Math.floor()とMath.random()を使います。
まず、Math.floor()を呼び出します。
Math.floor()の引数で、Math.random()の戻り値に最大値から最小値を引いた値を掛けます。
そして、Math.floor()の戻り値に最小値を足します。
//max=範囲の最大値、min=範囲の最小値
var random = Math.floor(Math.random() * (max - min)) + min
上記のMath.floor()に最小値を足した値は、整数の乱数を特定の範囲で生成します。
使用例
for (var i = 0; i < 5; i++) {
console.log(Math.floor(Math.random() * (50 - 40)) + 40);
}
出力:
43
47
49
41
44
コメント