JavaScript Random

❮ 前章へ 次章へ ❯

Math.random()

Math.random() は、0 以上 1 未満の間の乱数を返します:

Math.random();              // returns a random number
Try it Yourself »

Math.random() は、常に 1 より小さい数値を返します。


JavaScript ランダム整数

Math.random() は、ランダムな整数を返すために Math.floor() と一緒に使用します。

Math.floor(Math.random() * 10);     // returns a number between 0 and 9
Try it Yourself »

Math.floor(Math.random() * 11);      // returns a number between 0 and 10
Try it Yourself »

Math.floor(Math.random() * 100);     // returns a number between 0 and 99
Try it Yourself »

Math.floor(Math.random() * 101);     // returns a number between 0 and 100
Try it Yourself »

Math.floor(Math.random() * 10) + 1;  // returns a number between 1 and 10
Try it Yourself »

Math.floor(Math.random() * 100) + 1; // returns a number between 1 and 100
Try it Yourself »

適切なランダム関数

上の例から分かるように、すべてのランダムな整数を目的に使用する適切なランダム関数を作成することをお勧めします。

この JavaScript 関数は、常に min(以上)と max(未満)の間の乱数を返します

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min) ) + min;
}
Try it Yourself »

この JavaScript 関数は、常に min と max の(両端を含む)間の乱数を返します:

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}
Try it Yourself »

❮ 前章へ 次章へ ❯