搜索吧

首页 » 搜成宝库 » 常用知识 » js实现随机数,随机整数,指定范围的随机数
xiaoyaoyou - 2009-4-17 20:28:57
在js代码中生成一个范围的整数,和java中的随机数生成还是有一定的区别的,在java2中是先声明一个random对象,然后调用nextInt(int n)方法就可以完成!

在js中,要用到是是Math

The above creates a random integer between 0 and 2. The number could be 0,1, or 2. Let's see more finely why this is the case.

1) Math.random() always produces a random number between 0 and 1
2) Math.random()*2 always produces a random number between 0 and 2
3) Math.round(Math.random()*2) always produces a random integer between 0 and 2,最大值可以取到2

例子:

<script type="text/javascript'>
function random_3(){
var myrandom=Math.round(Math.random()*2)
var link1="http://www.codingforums.com"
var link2="http://www.cssdrive.com"
var link3="http://www.dynamicdrive.com"
if (myrandom==0)
window.location=link1
else if (myrandom==1)
window.location=link2
else if (myrandom==2)
window.location=link3
}
</script>
<form>
<input type="button" value="random link!" onClick="random_3()">
</form>
1
查看完整版本: js实现随机数,随机整数,指定范围的随机数