JavaScript 随机生成 0 或 1 个整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45136711/
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
JavaScript random generate 0 or 1 integer
提问by Alexander Elgin
I am trying to generate random 0 or 1 as I am writing a script to populdate my database. If it is 1, I will save it as male and 0 the other way around.
我正在尝试生成随机 0 或 1,因为我正在编写一个脚本来填充我的数据库。如果它是 1,我会将它保存为男性,反之则保存为 0。
Inside my JavaScript:
在我的 JavaScript 中:
Math.floor((Math.random() * 1) + 1);
I used this to generate either 1 or 0. However, with the code above, it always return me with 1. Any ideas?
我用它来生成 1 或 0。但是,使用上面的代码,它总是返回 1。有什么想法吗?
回答by Alexander Elgin
You can use Math.round(Math.random()). If Math.random()generates a number less than 0.5 the result will be 0 otherwise it should be 1.
您可以使用Math.round(Math.random()). 如果Math.random()生成的数字小于 0.5,则结果将为 0,否则应为 1。
回答by brk
There is a +1with Math.random, so it will always going to add 1 to the randomly generated number.
You can just randomly generate a number, since Math.random will generate any floating number between 0 & 1 , then use if.. else to use Math.floor & Math.ceil
有一个+1with Math.random,所以它总是会在随机生成的数字上加 1。您可以随机生成一个数字,因为 Math.random 将生成 0 和 1 之间的任何浮点数,然后使用 if.. else 使用 Math.floor & Math.ceil
var y =Math.random();
if(y<0.5){
y =Math.floor(y)
}
else{
y= Math.ceil(y)
}
console.log(y)

