开心生活站

位置:首页 > IT科技 > 

js获取随机数

IT科技1.7W
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

js获取随机数怎么操作?一起来看看小编今天的分享吧!

JavaScript可以使用 Math(算数) 对象来实现随机数的生成。Math 对象用于执行数学任务。且Math 对象并不像 Date 和 String 那样是对象的类,因此没有构造函数 Math()。

js 可以使用 Math(算数) 对象来实现随机数的生成。

首先需要了解的 Math 对象方法。

ceil(x):对数进行上舍入,即向上取整;

floor(x):对 x 进行下舍入,即向下取整;

round(x):四舍五入;

random() 返回 0 ~ 1 之间的随机数,包含 0 不包含 1。

一些实例说明:

Math.ceil(Math.random()*10);     // 获取从 1 到 10 的随机整数,取 0 的概率极小。Math.round(Math.random());       // 可均衡获取 0 到 1 的随机整数。Math.floor(Math.random()*10);    // 可均衡获取 0 到 9 的随机整数。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。所以头尾的分布区间只有其他数字的一半。

生成 [n,m] 的随机整数:

函数功能:生成 [n,m] 的随机整数,在 js 生成验证码或者随机选中一个选项时很有用。

//生成从minNum到maxNum的随机数function randomNum(minNum,maxNum){     switch(arguments.length){         case 1:             return parseInt(Math.random()*minNum+1,10);         break;         case 2:             return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10);         break;             default:                 return 0;             break;     } }

过程分析:

Math.random() 生成 [0,1) 的数,所以 Math.random()*5 生成 {0,5) 的数。

通常期望得到整数,所以要对得到的结果处理一下。

parseInt(),Math.floor(),Math.ceil() 和 Math.round() 都可得到整数。

parseInt() 和 Math.floor() 结果都是向下取整。

所以 Math.random()*5 生成的都是 [0,4] 的随机整数。

js获取随机数

所以生成 [1,max] 的随机数,公式如下:

// max - 期望的最大值parseInt(Math.random()*max,10)+1;Math.floor(Math.random()*max)+1;Math.ceil(Math.random()*max);

所以生成 [0,max] 到任意数的随机数,公式如下:

// max - 期望的最大值parseInt(Math.random()*(max+1),10);Math.floor(Math.random()*(max+1));

所以希望生成 [min,max] 的随机数,公式如下:

// max - 期望的最大值// min - 期望的最小值parseInt(Math.random()*(max-min+1)+min,10);Math.floor(Math.random()*(max-min+1)+min);
标签:随机数 js 获取