生成随机数字

Math.random, returns a floating-point, pseudo-random number in the range [0, 1)

[0,1)

  1. // Returns a random number between 0 (inclusive) and 1 (exclusive)
  2. function getRandom() {
  3. return Math.random();
  4. }

[min, max)

  1. // Returns a random number between min (inclusive) and max (exclusive)
  2. function getRandomArbitrary(min, max) {
  3. return Math.random() * (max - min) + min;
  4. }

[min, max)整数

  1. // Returns a random integer between min (included) and max (excluded)
  2. // Using Math.round() will give you a non-uniform distribution!
  3. function getRandomInt(min, max) {
  4. return Math.floor(Math.random() * (max - min)) + min;
  5. }

参考资料

原文: https://leohxj.gitbooks.io/front-end-database/content/problems-in-develop-webapp/generate-random.html