我想在Javascript中使用随机函数?

时间:2012-03-29 15:27:00

标签: javascript random

var x = 1 + Math.Random() % 9;
if (x==1)
    // do something
else if (x==2) 
    // do something else

我在C ++中使用了这一行 - (1 + Math.Random() % 9)来获得1到9之间的数字,但在JavaScript中我得到了不同的结果。

4 个答案:

答案 0 :(得分:3)

Math.random()返回01之间的值,因此您需要使用模运算符来使用乘法。

1 + (Math.random() * 9);

最后,您应该舍入或.floor()该值

var x = Math.floor( 1 + ( Math.random() * 9 ) );

或更短

var x = ~~( 1 + ( Math.random() * 9 ) );

答案 1 :(得分:1)

JavaScript中没有Math.Random()函数。它是Math.random()。注意大写。

要获取某个最小值和最大值之间的随机数,请执行以下操作:

var min = 1, max = 9;
Math.floor(Math.random() * (max - min + 1)) + min;

进一步阅读: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random

答案 2 :(得分:1)

在Javascript中,Math.random函数返回0到1之间的数字。如果要获得1到9之间的数字,您将不得不使用它。

var number = ((Math.random() * 10) | 0) % 9 + 1

答案 3 :(得分:0)

这将为您提供0到9之间的结果

Math.floor(Math.random()*9) 

顺便说一下,jQuery是一个javascript框架。 Math是一个原生的javascript函数