How to Generate a random number of fixed length using JavaScript?

前端 未结 22 2350
攒了一身酷
攒了一身酷 2021-01-30 10:23

I\'m trying to generate a random number that must have a fixed length of exactly 6 digits.

I don\'t know if JavaScript has given below would ever create a number less th

相关标签:
22条回答
  • 2021-01-30 10:50

    I was thinking about the same today and then go with the solution.

    var generateOTP = function(otpLength=6) {
      let baseNumber = Math.pow(10, otpLength -1 );
      let number = Math.floor(Math.random()*baseNumber);
      /*
      Check if number have 0 as first digit
      */
      if (number < baseNumber) {
        number += baseNumber;
      }
      return number;
    };
    

    Let me know if it has any bug. Thanks.

    0 讨论(0)
  • 2021-01-30 10:50

    You can use this module https://www.npmjs.com/package/uid, it generates variable length unique id

    uid(10) => "hbswt489ts"
     uid() => "rhvtfnt" Defaults to 7
    

    Or you can have a look at this module https://www.npmjs.com/package/shortid

    const shortid = require('shortid');
    
    console.log(shortid.generate());
    // PPBqWA9
    

    Hope it works for you :)

    0 讨论(0)
  • 2021-01-30 10:52

    This is another random number generator that i use often, it also prevent the first digit from been zero(0)

      function randomNumber(length) {
        var text = "";
        var possible = "123456789";
        for (var i = 0; i < length; i++) {
          var sup = Math.floor(Math.random() * possible.length);
          text += i > 0 && sup == i ? "0" : possible.charAt(sup);
        }
        return Number(text);
      }

    0 讨论(0)
  • 2021-01-30 10:53

    More generally, generating a random integer with fixed length can be done using Math.pow:

    var randomFixedInteger = function (length) {
        return Math.floor(Math.pow(10, length-1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length-1) - 1));
    }
    

    To answer the question: randomFixedInteger(6);

    0 讨论(0)
提交回复
热议问题