代码改变世界

JS随机数

2014-10-09 14:42  彭大先生  阅读(266)  评论(0编辑  收藏  举报

首先JavaScript的中Math对象的几个方法:

Math.random()  产生0~1之间的随机数,是一个很长的小数

Math.ceil() 对上进行舍入

Math.floor()对下进行舍入

Math.round()四舍五入

那么产生随机数

function randomNum(){
       return Math.random();   
}

产生指定区间的随机数

function randomNum(m,n){
            return Math.floor(Math.random() * (n-m+1) + m);;
        }        
    console.log(randomNum(1,4));//产生结果 1 ,2 ,3 ,4 四种