JavaScriptランダム
Math.random()
Math.random()
0(包括的)から1(排他的)までの乱数を返します。
例
// Returns a random number:
Math.random();
Math.random()
常に1未満の数値を返します。
JavaScriptのランダムな整数
Math.random()
で使用すると、Math.floor()
ランダムな整数を返すために使用できます。
JavaScript整数のようなものはありません。
ここでは、小数点のない数値について話します。
例
// Returns a random integer from 0 to 9:
Math.floor(Math.random() * 10);
例
// Returns a random integer from 0 to 10:
Math.floor(Math.random() * 11);
例
// Returns a random integer from 0 to 99:
Math.floor(Math.random() * 100);
例
// Returns a random integer from 0 to 100:
Math.floor(Math.random() * 101);
例
// Returns a random integer from 1 to 10:
Math.floor(Math.random() * 10) + 1;
例
// Returns a random integer from 1 to 100:
Math.floor(Math.random() * 100) + 1;
適切なランダム関数
上記の例からわかるように、すべてのランダムな整数の目的に使用する適切なランダム関数を作成することをお勧めします。
このJavaScript関数は、常にmin(含まれる)とmax(除外される)の間の乱数を返します。
例
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
このJavaScript関数は、常に最小値と最大値(両方を含む)の間の乱数を返します。
例
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}