ceil()
向上取整,可以理解为去点小数点后再加1
floor()
向下取整,可以理解为去点小数点
<script>
document.write(Math.ceil(25.5)); //结果是向上取整,26
document.write(Math.floor(25.5)); //结果是向下取整,25
</script>
round()
四舍五入为最接近的值,但是负数小数为.5的时候,直接去点.5显示。
<script>
document.write(Math.round(23.1)); //四舍五入接近23,返回值是23
document.write(Math.round(23.7)); //四舍五入接近24,返回值是24
document.write(Math.round(23.5)); //四舍五入接近24,返回值是24
document.write(Math.round(-23.5)); //round的特殊情况负数的.5,直接去掉.5,返回值是-23
</script>
random()
返回值是随机数,0 <= 随机数 < 1;
公式:Math.floor(Math.random() * (最大值 - 最小值 + 1)) + 最小值;【包含最大值
公式:Math.floor(Math.random() * (最大值 - 最小值 )) + 最小值;【不包含最大值
使用该公式可以在最小值和最大值之间随机取值十位。
<!-- 使用Math对象随机产生10到100的十个数字,并对这十个随机数去重排序 -->
<script>
var arr = [];
for (var i = 0; i < 10; i++) {
let num = Math.floor(Math.random() * (100 - 10 + 1) + 10);
if (arr.indexOf(num) == -1) { //还可以用includes取反
arr.push(num);
}
}
arr.sort(function (a, b) {
return a - b;
});
document.write(arr);
</script>
pow()
pow(a,b)返回值是a的b次方
<script>
document.write(Math.pow(3,2)); //3的二次方。3*3=9
</script>