Generate random number between two numbers in JavaScript

后端 未结 23 2090
走了就别回头了
走了就别回头了 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:26

    Math.random()

    Returns an integer random number between min (included) and max (included):

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

    Or any random number between min (included) and max (not included):

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

    Useful examples (integers):

    // 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;
    

    ** And always nice to be reminded (Mozilla):

    Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.

提交回复
热议问题