1、Math 是一个内置对象,不是一个函数对象。
2、Math 作为内置对象,拥有一些数学常数属性和数学函数方法。
3、 如果Math 用于 Number 类型。它不支持 BigInt。
4、Math 的所有属性是静态的,Math方法也全部都是静态方法。
//引用圆周率
document.write(Math.PI)
//abs() 求一个数的绝对值
document.write(Math.abs(90))
//max()求最大值
document.write(Math.max(23,45,67,89))
//min()求最小值
document.write(Math.min(23,45,67,89,100))
//pow(a,b) 求a的b次方
document.write(Math.pow(2,5))
//random()返回0-1之间的小数[0,1)
document.write(Math.random())
//返回比1.2大的整数中 最小的那个
document.write(Math.ceil(1.2))
//返回比1.9小的那堆数中 最大的整数
document.write(Math.floor(1.9))
//四舍五入
document.write(Math.round(1.5))
//只截取整数
document.write(Math.trunc(9.9))
练习1:
<script>
//定义一个函数,随机产生一个rgb颜色
//rgb(0,0,225)
var getColor=function(){
//产生红色的值:[0,225]的整数
let red=Math.round(Math.random()*255) //[0,1) [0,255)的小数
let green=Math.round(Math.random()*255)
let blue=Math.round(Math.random()*225)
return 'rgb('+red+','+green+','+blue+')'
}
let color1=getColor()
document.write(color1)
//为body元素设置color样式
document.body.style.color=color1
</script>
运行结果:
练习2(举一反三): 如何设置body的背景图?
<script>
//定义一个函数,设置body的背景图
//图片路径存放在数组里,
//如何随机产生一个数组的下标?用floor有什么需要考虑的?
function getImg(){
let arr=['./img/1.jpg','./img/2.jpg','./img/3.jpg']
let index=Math.floor(Math.random()*(arr.length))
return arr[index];
}
let r=getImg()
document.body.style.backgroundImage='url('+r+')'
</script>