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

前端 未结 22 2352
攒了一身酷
攒了一身酷 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.

提交回复
热议问题