关于Math对象的常用方法
Math.PI—>Π
Math.abs(值);—>取绝对值
Math.ceil(值);—>向上取整
Math.floor(值);—>向下取整
Math.round(值);—>四舍五入
Math.max(值1,值2,值3…);—>取最大值
Math.min(值1,值2,值3…);—>取最小值
Math.pow(值1,值2);—>次方
Math.sqrt(值1);—>开方
Math.random();—>随机数
例子:自定义一个对象,来实现系统的max的方法
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 maxNum=new MyMax();
console.log(maxNum.getMax(10,20,30));//打印结果为30
例:随机产生一个十六进制的颜色值,例如#cccccc
function getColor(){
var color="#";
//随机取六个字符,然后拼接
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++){
color+=arr[Math.ceil(Math.random()*15)];
}
return color;//返回随机的颜色值
}
console.log(getColor());