手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >使用Math.floor与Math.random取随机整数的方法详解
使用Math.floor与Math.random取随机整数的方法详解
摘要:Math.random():获取0~1随机数Math.floor()methodroundsanumberDOWNWARDStothenea...

Math.random():获取0~1随机数

Math.floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result. (小于等于 x,且与 x 最接近的整数。)

其实返回值就是该数的整数位:

Math.floor(0.666) --> 0

Math.floor(39.2783) --> 39

所以我们可以使用Math.floor(Math.random())去获取你想要的一个范围内的整数。

如:现在要从1~52内取一个随机数:

首先Math.random()*52 //这样我们就能得到一个 >=0 且 <52的数

然后加1:Math.random()*52 + 1 //现在这个数就 >=1 且 <53

再使用Math.floor取整

最终: Math.floor(Math.random()*52 + 1)

这就能得到一个取值范围为1~52的随机整数了.

【使用Math.floor与Math.random取随机整数的方法详解】相关文章:

JS或jQuery获取ASP.NET服务器控件ID的方法

简介JavaScript中用于处理正切的Math.tan()方法

jQuery仿gmail实现fixed布局的方法

在JavaScript中使用开平方根的sqrt()方法

JavaScript获取并更改input标签name属性的方法

Jquery解析json字符串及json数组的方法

javascript操作ul中li的方法

js+cookies实现悬浮购物车的方法

JSON字符串和对象之间的转换详解

JavaScript获取当前运行脚本文件所在目录的方法

精品推荐
分类导航