在对随机数字的使用上,用到最多的时候大概就是抽奖了,这也是很多人都喜欢的环节。那么在js中我们怎么对数字进行随机输出呢?这里我们可以使用random()函数来进行随机数字的操作,不过要先对它的概念、语法、返回值做到了解,然后为大家带来random()随机生成1到100的实例。
1.random()概念
返回的数值是[0.0,1.0)的double型数值,由于double类数的精度很高,可以在一定程度下看做随机数,借助(int)来进行类型转换就可以得到整数随机数了,代码如下。
2.语法
Math.random()
3.返回值
Number,0.0 ~ 1.0(不包含) 之间的一个伪随机数。
4.实例
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Test</title>
<scripttype="text/javascript"src="jquery-1.10.2.min.js"></script>
<scripttype="text/javascript">
functioncheckNum(){
varrandom=getRandom(0,100);
varv=$("#input").val();
alert("random:"+random+",input:"+v);
if(random==v)
window.close();
}
functiongetRandom(min,max){
varr=Math.random()*(max-min);
varre=Math.round(r+min);
re=Math.max(Math.min(re,max),min)
returnre;
}
</script>
</head>
<body>
<inputid="input"type="input"value="23"/>
<buttononclick="checkNum()">ok</button>
</body>
</html>
原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
















































暂无评论内容