JavaScript 学习笔记——Math属性及其方法

Math.random() -- 返回0和1之间的伪随机数 可能为0,但总是小于1,[0,1)。

 

1 Math.random()*10//返回 0-10 之间的随机数。
2                                            
3 Math.random()*(20-10)+10 //返回10-20之间的随机数。
4                                            
5 Math.random()*(n-m)+m //返回(m-n)之间的随机数。

Math.floor() -- 向下取得一个最接近的整数

Math.floor(12.2)// 返回12 
                                        
Math.floor(12.7)//返回12 
                                        
Math.floor(12.0)//返回12

Math.ceil() -- 向上取得一个最接近的整数

Math.ceil(12.2)//返回13 
                                 
Math.ceil(12.7)//返回13 
                                 
Math.ceil(12.0)// 返回12

Math.round() -- 进行四舍五入

Math.round(12.2)// 返回12 
                            
Math.round(12.7)//返回13 
                            
Math.round(12.0)//返回12

这些函数平常实际使用中大多相互配合:例如要想生成 0 - 10 之间的随机整数,可以这样写

Math.floor(Math.random()*10);

//其中Math.random()*10返回 [0 - 10)之间的随机数,再利用Math.floor(),只取出其中的整数。
Math.ceil(Math.random()*10);

//那么依据上述介绍,这样因为Math.ceil()向上取整,那么则返回 [1 - 10] 之间的随机整数。
原文地址:https://www.cnblogs.com/rguanghui/p/2889814.html