Math对象
//Math.PI=====π
//Math.abs(值)====取绝对值
console.log(Math.abs(-4));//4
//Math.ceil(值)====向上取整
console.log(Math.ceil(2.2));//3
//Math.floor(值)===向下取整
console.log(Math.floor(2.2));//2
//Math.round(值)====四舍五入
console.log(Math.round(2.5));//3
//Math.max(值一,值二,值三.....)取一堆数中的最大值
console.log(Math.max(1,2,3,4,5))//5
//Math.min(值一,值二,值三.....)取一堆数中的最小值
console.log(Math.min(1,2,3,4,5))//1
//Math.pow(值一,值二) 次方
console.log(Math.pow(2,3))//8
//Math.sqrt(值一) 平方根
console.log(Math.sqrt(25))//5
//Math.random() 随机数
console.log(Math.floor(Math.random()*5))//去0-4的随机整数
Math对象的应用
- 让整个屏幕自动更换颜色
首先我们在body中添加一个div,并给body和div都设置样式
<style>
body,html{
width: 100%;
height: 100%;
}
#box{
width: 100%;
height: 100%;
}
</style>
然后我们就可以开始写js的代码了
//随机产生一个十六进制的颜色值
function getColor() {
var str="#";
//十六个字符随机取六个,然后拼接
var arr=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
//遍历六次随机数
for (var i=0;i<6;i++){
//0-15
var num= parseInt(Math.random()*16);
str=str+arr[num];
console.log(str);
}
return str;
}
最后我们通过id来获取到上面个他添加的div,再给它添加一个计时器,让整个屏幕可以"动"起来,这样就大功告成了
//通过id获取这个元素
setInterval(
function () {
document.getElementById("box").style.backgroundColor=getColor();
},100
)
2.定义一个对象来实现求一组数的最大值
function MyMax() {
//添加方法
this.getMax=function () {
//假设一个最大值
var max=arguments[0];//获取实参的个数,以数组的形式呈现的
for (var i=0;i<arguments.length;i++) {
if (max<arguments[i]){
max=arguments[i];
}
}
return max;
}
}
var m=new MyMax();
console.log(m.getMax(1, 2, 3, 4, 5, 6)