LoginSignup
4
2

More than 5 years have passed since last update.

[Javascript] ランダムな数字を出力する

Posted at

乱数を出力するプログラム

0~10の間のランダムな値を返す

var rand = Math.floor(Math.random() * 11);

console.log( rand );
=> 3 // 実行するごとに1~10の範囲でランダムな値を返す

0~引数に渡した値より小さい乱数を返す関数


function randomInt(num){
  var rand = Math.floor(Math.random() * num);

  return rand;
}


randomInt(100);
=> 78 // 実行するごとに1~10の範囲でランダムな値を返す

最大値と最小値を渡し、ランダムな値を返す


function randomIntMinMax(min, max){
  var rand = Math.floor(Math.random() * (max + 1 - min)) + min

  return rand
}

randomIntMinMax(10, 100);
=> 78 // 実行するごとに10~100の範囲でランダムな値を返す
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2