为什么此代码不生成数字0?

时间:2019-12-03 12:37:46

标签: javascript

想知道为什么我的代码没有生成数字零,所以每个数字都是从1-9随机生成的。

我需要更改以包括0-9范围。

function GenerateCaptcha() {
var chr1=Math.ceil(Math.random() * 9)+ '';

非常感谢

5 个答案:

答案 0 :(得分:5)

MDN doc

  

Math.ceil()函数始终将数字四舍五入到下一个最大的整数或整数。

这意味着,如果您得到的数字介于0到1之间,则将四舍五入为1。

您可以保持原样,或改用Math.floor

或者更好,Math.round,如Levi Johansen所建议。这将舍入到最接近的整数。

答案 1 :(得分:4)

您可以使用超短版本~~(Math.random() * 10)生成一个介于0到9之间的数字

console.log(~~(Math.random() * 10))

答案 2 :(得分:2)

Math.ceil(Math.random() * 9)+ '';替换为Math.floor(Math.random() * 9)+ '';

答案 3 :(得分:2)

使用Math.floor()生成0作为随机数之一。

答案 4 :(得分:0)

要生成0,您需要使用Math.floor()代替Math.ceil

例如

function GenerateCaptcha() {
var chr1=Math.floor(Math.random() * 9)+ '';

Math.ceil如果小于1,即0.xxx,则给出1。

Math.floor在数字为0时给出0。大于0且小于1。即从0.0到0.99

相关问题