「JavaScript」Math.randomで乱数を取得する
書式
Math.random() * 範囲数字
Math.random() * 範囲数字
Math.random() * 範囲数字
Math.random()を使用して、乱数を取得します。
Math.random()の戻り値は、0以上1未満の小数値が取得できますので、数値に整形して使用します。
使用例
//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);
実行結果
3
33
14
3
33
14
3 33 14