javascript 固定长度的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8476152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random number with fixed length
提问by skywind
I want to generate a random integer number with 0-9 numbers and with length = 5. I try this:
我想用 0-9 个数字和长度 = 5 生成一个随机整数。我试试这个:
function genRand(min,max) {
for (var i = 1; i <= 5; i++) {
var range = max - min + 1;
return Math.floor(Math.random()*range) + min;
}
}
and call:
并调用:
genRand(0,9);
But it always returns 1 number, not 5 (
但它总是返回 1 个数字,而不是 5 个(
Help please!
请帮忙!
回答by Nate B
function genRand() {
return Math.floor(Math.random()*89999+10000);
}
回答by graphicdivine
return
exits the function on the first loop.
return
在第一个循环中退出函数。
回答by kennebec
The smallest 5 digit number is 10000, the largest is 99999, or 10000+89999.
最小的 5 位数字是 10000,最大的是 99999,或 10000+89999。
Return a random number between 0 and 89999, and add it to the minimum.
返回 0 到 89999 之间的随机数,并将其添加到最小值。
var ran5=10000+Math.round(Math.floor()*90000)
Math.floor rounds down, and Math.random is greater than or equal to 0 and less than 1.
Math.floor 向下取整,Math.random 大于等于 0 小于 1。
回答by Airhogs777
Here's a more generalized version of Nate B's answer:
这是 Nate B 答案的更概括版本:
function rand(digits) {
return Math.floor(Math.random()*parseInt('8' + '9'.repeat(digits-1))+parseInt('1' + '0'.repeat(digits-1)));
}
回答by phoxis
To get a 5 digit random number generate random numbers between the range (10000, 99999). Or generate randomly 5 single digits and paste them.
要获得 5 位随机数,请生成范围 (10000, 99999) 之间的随机数。或随机生成 5 个个位数并粘贴它们。
EDIT
编辑
The process you have shown simply will generate one number and return to the caller. The think which might work is (pseudo code) :
您所展示的过程只会生成一个号码并返回给调用者。可能有效的想法是(伪代码):
int sum = 0;
int m = 1;
for (i=0;i<5;i++)
{
sum = sum + m * random (0, 9);
/* or */
sum = sum * m + random (0, 9);
m = m * 10;
}
Or better generate 5 digit random numbers with rand (10000, 99999)
或者更好地生成 5 位随机数 rand (10000, 99999)