JavaScript 随机生成 0 或 1 的整数

83
我正在尝试生成随机的0或1,因为我正在编写一个脚本来填充我的数据库。如果是1,我将把它保存为男性,如果是0,则反之。
在我的JavaScript中:
Math.floor((Math.random() * 1) + 1);

我用这个代码生成了1或0。但是,使用上面的代码,它总是返回给我1。有任何想法吗?


2
Math.floor(Math.random() + 0.5); - shiyon sufa
2个回答

223

你可以使用 Math.round(Math.random())。如果 Math.random() 生成的数字小于0.5,结果将为0,否则应该为1。


25
让变量 oneOrZero 等于随机产生的 0 和 1 中的一个,概率各为一半。可以用以下代码实现:(Math.random()>0.5)? 1 : 0; - Combine
3
谢谢你节省了我的脑细胞。 :) - clockworked247
7
应该这样写才对:let oneOrZero = (Math.random()>=0.5)? 1 : 0; - Chad Johnson
使用 Chad Johnson 的 fifty-fifty。 - wlf

2

在 Math.random 中有一个 +1,因此它总是会将随机生成的数字加 1。 你可以随机生成一个数字,因为 Math.random 会生成介于 0 和 1 之间的任何浮点数,然后使用 if.. else 来分配 0 或 1。

var y = Math.random();
if (y < 0.5)
  y = 0
else
  y= 1
console.log(y)


3
console.log(Math.random()<0.5?0:1) - pbies

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接