javascript 如何在javascript中获取一位数的随机数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14122894/
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
How to get one digit random number in javascript?
提问by Gowsikan
Possible Duplicate:
Generating random numbers in Javascript in a specific range?
Can some one tell me how to get one digit random number(1,2,3,.. not 0.1,0.2,.. or 1.0,5.0,..) using Math.random() or some other way in javascript?
有人可以告诉我如何使用 Math.random() 或 javascript 中的其他方式获得一位随机数(1,2,3,.. 不是 0.1,0.2,.. 或 1.0,5.0,..)?
回答by Blender
Math.random()
returns a float between 0
and 1
, so just multiply it by 10
and turn it into an integer:
Math.random()
返回0
和之间的浮点数1
,因此只需将其乘以10
并将其转换为整数:
Math.floor(Math.random() * 10)
Or something a little shorter:
或者更短的东西:
~~(Math.random() * 10)
回答by JohannesB
DISCLAIMER:
免责声明:
JavaScript's math.rand() is notcryptographically secure, meaning that this should NOTbe used for password, PIN-code and/or gambling related random number generation. If this is your use case, please use the web crypto APIinstead! (w3c)
JavaScript 的 math.rand()不是加密安全的,这意味着它不应用于密码、PIN 码和/或与赌博相关的随机数生成。如果这是您的用例,请改用网络加密 API!( w3c)
If the digit 0 is not included (1-9):
如果不包括数字 0 (1-9):
function randInt() {
return Math.floor((Math.random()*9)+1);
}
If the digit 0 is included (0-9):
如果包含数字 0 (0-9):
function randIntWithZero() {
return Math.floor((Math.random()*10));
}
回答by Paul Collingwood
var randomnumber=Math.floor(Math.random()*10)
where 10 dictates that the random number will fall between 0-9.
其中 10 表示随机数将介于 0-9 之间。
回答by Tanzeel Kazi
Use this:
用这个:
Math.floor((Math.random()*9)+1);
回答by gopi1410
Math.floor((Math.random()*10));
And there goes your random integer between 0 and 10!
你的随机整数在 0 到 10 之间!