Generate random number between two numbers in JavaScript

有什么方法可以在JavaScript中的指定范围内生成一个随机数(例如从1到6:1,2,3,4,5或6)?


If you wanted to get between 1 and 6, you would calculate:

Math.floor(Math.random() * 6) + 1  

Where:

  • 1 is the start number
  • 6 is the number of possible results (1 + start (6) - end (1))

  • function randomIntFromInterval(min,max)
    {
        return Math.floor(Math.random()*(max-min+1)+min);
    }
    

    What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.


    Math.random()

    From the Mozilla Developer Network documentation:

    // Returns a random integer between min (included) and max (included)
    
    function getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    

    Useful examples:

    // 0 -> 10
    Math.floor(Math.random() * 11);
    
    // 1 -> 10
    Math.floor(Math.random() * 10) + 1;
    
    // 5 -> 20
    Math.floor(Math.random() * 16) + 5;
    
    // -10 -> (-2)
    Math.floor(Math.random() * 9) - 10;
    
    链接地址: http://www.djcxy.com/p/2926.html

    上一篇: 用Java获取随机数

    下一篇: 在JavaScript中生成两个数字之间的随机数