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

前端 未结 22 2726
攒了一身酷
攒了一身酷 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:43

    In case you also want the first digit to be able to be 0 this is my solution:

    const getRange = (size, start = 0) => Array(size).fill(0).map((_, i) => i + start);
    
    const getRandomDigit = () => Math.floor(Math.random() * 10);
    
    const generateVerificationCode = () => getRange(6).map(getRandomDigit).join('');
    
    console.log(generateVerificationCode())

提交回复
热议问题