如何使用JavaScript生成一个固定长度的随机数? [英] How to Generate a random number of fixed length using JavaScript?
问题描述
我正在尝试生成一个必须具有正好6位数字的固定长度的随机数。
I'm trying to generate a random number that must have a fixed length of exactly 6 digits.
我不知道JavaScript是否会在下面给出创建一个小于6位的数字?
I don't know if JavaScript has given below would ever create a number less than 6 digits?
Math.floor((Math.random()*1000000)+1);
我在StackOverflow上找到了这个问题和答案此处。但是,目前还不清楚。
I found this question and answer on StackOverflow here. But, it's unclear.
编辑:我多次运行上面的代码,是的,它经常创建少于6位的数字。有快速/快速的方法来确保它总是正好是6位吗?
I ran the above code a bunch of times, and Yes, it frequently creates numbers less than 6 digits. Is there a quick/fast way to make sure it's always exactly 6 digits?
推荐答案
console.log(
Math.floor(100000 + Math.random() * 900000)
);
将始终创建6位数字,并确保第一个数字永远不会为0.您的问题中的代码将创建一个少于6位的数字。
Will always create a number of 6 digits and it ensures the first digit will never be 0. The code in your question will create a number of less than 6 digits.
这篇关于如何使用JavaScript生成一个固定长度的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!