2013-01-02 21 views
4

可能重复:
Generating random numbers in Javascript in a specific range?如何在javascript中获取一位数的随机数?

有人能告诉我如何获得一个数字的随机数(1,2,3,......不0.1,0.2,..或1.0 ,5.0,..)使用Math.random()或其他方式在JavaScript?

+1

可能重复:[生成的Javascript随机数在特定范围内?](http://stackoverflow.com/questions/1527803/), [在Javascript中的两个数字之间的随机数](http://stackoverflow.com/questions/4959975),[在JavaScript和-10和10之间的随机数](http://stackoverflow.com/questions/3594177), – mellamokb

回答

4
var randomnumber=Math.floor(Math.random()*10) 

其中10指示随机数将在0-9之间。

+0

10是不是一位数字,是吗? – JJJ

+0

哈哈,不,但是假设它是OP不希望的小数部分,他们可以解决它!编辑。 –

1

使用此:

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

'+ 1'删除'0'并将'10'添加到可能的输出中。 – Blender

+1

问题说“数字”,所以我认为它的意思是“0-9”。 – Blender

+0

@Blender好吧,你说得对'10'不是一个数字。我已经相应地纠正了它,但是OP的例子并没有包含'0',所以我认为这没问题。 –

1
Math.floor((Math.random()*10)); 

那还有0到10之间的随机整数!

12

Math.random()返回01之间的浮动,所以只通过10乘它,把它变成一个整数:

Math.floor(Math.random() * 10) 

或者其他更短一点:

~~(Math.random() * 10) 
+2

不错,不知道'~~'运算符 – C5H8NNaO4

2

如果数字0不包括(1-9):

function randInt() { 
    return Math.floor((Math.random()*9)+1); 
} 

如果数字0被包括(0-9):

function randIntWithZero() { 
    return Math.floor((Math.random()*10)); 
} 
相关问题