js获取随机数
2024-08-28 14:27:43
js 获取随机数方法如下:
1.Math.random()表示 结果为0-1间的一个随机数(包括0,不包括1) ;
返回指定范围的随机数(m-n之间)的公式
Math.random()*(n-m)+m;
Math.random()*10+5; //返回5-15之间的随机数
2.Math.ceil(n) 返回大于等于n的整数
用Math.ceil(Math.random()*10);时,主要获取1到10的随机整数,取0的几率极小。
3、Math.round(n); 返回n四舍五入后整数的值。
用Math.round(Math.random());可均衡获取0到1的随机整数。
用Math.round(Math.random()*10);时,可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10
的几率少一半。
4、Math.floor(n); 返回小于等于n的最大整数。
用Math.floor(Math.random()*10);时,可均衡获取0到9的随机整数。
5、基于时间,亦可以产生随机数
var now=new Date();
var number = now.getSeconds(); //这将产生一个基于目前时间的0到59的整数。 var now=new Date();
var number = now.getSeconds()%43; //这将产生一个基于目前时间的0到42的整数。
参考来源:http://www.studyofnet.com/news/181.html
例子:js获取随机颜色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style type="text/css">
#box{width: 100px;height: 100px;margin: 20px auto;background-color: #c66;}
</style>
<body>
<div id="box" onclick="getColor();">box1</div>
<script type="text/javascript">
var x,y,z;
var oBox=document.getElementById('box');
function getColor(box){
x=Math.round(Math.random()*255);
y=Math.round(Math.random()*255);
z=Math.round(Math.random()*255);
oBox.style.backgroundColor='rgb('+x+','+y+','+z+')';
}
</script>
</body>
</html>
坚持下去,相信自己。
最新文章
- 我的LESS编译方案
- VScode调试Python
- 【COGS】894. 追查坏牛奶
- MVC数据验证
- c语言知识(2)
- 开源字体包缩减font-spider
- 转载:linux capability深入分析
- JQUERY1.9学习笔记 之基本过滤器(九) 小于选择器
- Chrome extension
- pod setup 报CocoaPods was not able to update the `master` repo 错误解决办法
- jQuery2.x源码解析(DOM操作篇)
- [js高手之路]html5 canvas动画教程 - 自己动手做一个类似windows的画图软件
- NVL2 这个函数,
- [ZJOI2007]报表统计
- 安装ubuntu系统及ubuntu安装Python的几点心得
- [日志分析] Access Log 日志分析
- Android破解学习之路(十五)—— 【Unity3D】洛菲斯的呼唤(Lophis roguelike)无限金币(道具)的实现 破解
- JS 自由变量---JS 学习笔记(三) 补充
- bug狩猎
- python 内置函数(一),低阶内置函数功能汇总