目录
Math是一个内置对象,具有数学常数和函数的属性和方法,用于执行数学任务。
4、Math.random 返回0.0~1.0之间的随机数(包括0,不包括1)
扫描二维码关注公众号,回复:
14891436 查看本文章
Math.floor(Math.random()*(max-min +1))+min 包含最大值,包含最小值
一、 Math对象
Math
是一个内置对象,具有数学常数和函数的属性和方法,用于执行数学任务。
二、Math对象方法
1、Math.ceil( ) 对数进行向上舍入
<script>
// ceil 对数进行向上舍入
document.write(Math.ceil(-24.6)+'<br>');
//返回-24
document.write(Math.ceil(25.5)+'<br>');
//返回26
document.write(Math.ceil(26.1)+'<br>');
//返回27
document.write(Math.ceil(-0.0000000001)+'<br>');
//返回-1
</script>
2、Math.floor() 对数进行向下舍入
<script>
// floor 对数进行向下舍入
document.write(Math.floor(-24.2)+'<br>');
//返回-25
document.write(Math.floor(25.5)+'<br>');
//返回25
document.write(Math.floor(-0.0000000001)+'<br>');
//返回-1
</script>
3、Math.round() 把数四舍五入为最接近的数
<script>
// 在负数情况下,当小数位是5的时候,不会五入,会舍去
document.write(Math.round(-24.2)+'<br>')
//返回-24
document.write(Math.round(-25.5)+'<br>')
//返回-25
document.write(Math.round(-25.6)+'<br>')
//返回-26
</script>
4、Math.random() 返回0.0~1.0之间的随机数(包括0,不包括1)
<script>
// 应用场景:随机抽奖
document.write(Math.random()+'<br>')
</script>
5、pow() 取方 第一个是底数,第二个数次方
<script>
// pow 取方 第一个是底数,第二个数次方
document.write(Math. pow(2,3)+'<br>')
//返回8
</script>
公式:
Math.floor(Math.random()*(max-min +1))+min 包含最大值,包含最小值
<script>
// 去重随机抽取10~100以内十个数
let arr = []
let arr1 = []
for (var i = 0; i < 10; i++) {
arr.push(Math.floor(Math.random() * (100 - 10 + 1)) + 10);
// if (arr1.indexOf(arr[i]) == -1) {
// arr1.push(arr[i])
// }
if(!arr1.includes(arr[i])){
arr1.push(arr[i])
}
}
document.write(arr1.sort(function (a, b) {
return a - b
}));
</script>