欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

js生成随机数min,max的方法实例

程序员文章站 2022-03-30 19:28:36
...
本文我们主要和大家分享js生成随机数min,max的方法实例,希望能帮助到大家。

一、js的Math(算数)对象知识

通常我们希望得到的数会是整数

而Math.ceil(),Math.floor(),Math.round(),parseInt()都可以得到整数,现在来看一下他们的区别。

Math.ceil();    //向上取整。
Math.floor();    //向下取整。
parseInt();    //向下取整。
Math.round();    //四舍五入。
Math.random();    //0.0 ~ 1.0 之间的一个伪随机数。[0,1)  包含0,不包含1。
Math.ceil(Math.random()*10);      // 获取从1到10的随机整数 ,取0的概率极小。当随机数取到0时,才返回0;取到0.1返回的是1。
Math.floor(Math.random()*10);    //可均衡获取0到9的随机整数。
parseInt(Math.random()*10);    //可均衡获取0到9的随机整数。
Math.round(Math.random());     //可均衡获取0到1的随机整数。
Math.round(Math.random()*10);    //基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。

当随机数取到0~0.4返回0,0.5~1.4返回1……8.5~9.4返回9,9.5~9.9返回10。所以头尾的分布区间只有其他数字的一半。

二、实际需求

生成[0,max]的随机数

Math.floor(Math.random()*(max+1));
parseInt(Math.random()*(max+1));
生成[1,max]的随机数
Math.floor(Math.random()*10)+1;
parseInt(Math.random()*10)+1;
生成[min,max]的随机数
Math.floor(Math.random()*(max-min)+min);
parseInt(Math.random()*(max-min)+min);

三、函数实现

获取[min,max]的随机整数,可用在js生成验证码或者随机选中一个选项。

function randomNum(min,max){ 
	switch(arguments.length){ 
		case 1: 
			return parseInt(Math.random()*min+1); 
			break; 
		case 2: 
			return parseInt(Math.random()*(max-min+1)+minNum); 
			break; 
		default: 
			return 0; 
			break; 
	} 
}

相关推荐:

js生成随机数之random函数随机示例_javascript技巧

js生成随机数的方法实例_javascript技巧

js生成随机数的过程解析_javascript技巧

以上就是js生成随机数min,max的方法实例的详细内容,更多请关注其它相关文章!