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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:45:41  来源:igfitidea点击:

How to get one digit random number in javascript?

javascriptmathrandomdigit

提问by Gowsikan

Possible Duplicate:
Generating random numbers in Javascript in a specific range?

可能的重复:
在特定范围内的 Javascript 中生成随机数?

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 0and 1, so just multiply it by 10and 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 之间!