Generate random number between two numbers in JavaScript

后端 未结 23 2462
走了就别回头了
走了就别回头了 2020-11-22 01:09

Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?

23条回答
  •  清歌不尽
    2020-11-22 01:40

    jsfiddle: https://jsfiddle.net/cyGwf/477/

    Random Integer: to get a random integer between min and max, use the following code

    function getRandomInteger(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min)) + min;
    }
    

    Random Floating Point Number: to get a random floating point number between min and max, use the following code

    function getRandomFloat(min, max) {
      return Math.random() * (max - min) + min;
    }
    

    Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

提交回复
热议问题