html代码
Math.random()随机数四舍五入
时间:2023-12-27
Math.random方法用来取随机数,配合Math.round、Math.floor与Math.ceil可以方便取任意随机数。
一、用法
Math.random() |
返回0-1之间的任意数,不包括0和1 |
Math.round(num) |
num进行四舍五入 |
Math.floor(num) |
返回小于等于num的整数,相当于四舍五入的四舍,不五入 |
Math.ceil(num) |
返回大于等于num的最小整数 |
二、例子
console.log(Math.random());//返回随机数:0.43181758131649706 console.log(Math.round(16.7));//四舍五入返回:17 console.log(Math.floor(1.9));//返回1,1.0~1.9都返回1 console.log(Math.ceil(1.1));//返回2 ,与floor相反,1.0~1.9都返回2 console.log(Math.ceil(Math.random()));//结合上面的例子就知道,Math.random()返回值肯定小于1,这里向上取整返回1 console.log(Math.floor(Math.random())); //返回0 |
三、使用
返回指定范围的随机数:
random(size) { return Math.round(Math.random() * size); }, |