Math数学对象
本章单词
math 数学
PI 圆周率
max 最大
min 最小
floor 地板(去掉小数)
ceil 天花板(逢小数进1)
round 四舍五入
random 随机
abs absolute 绝对值
js里自带一些对象,供我们开发者使用,这些对象提前内置准备好了一些常用的属性和方法,我们直接拿来用就可以了。
比如:圆周率 3.1415926 Math.PI
Math内置对象 不是一个构造函数 所以直接使用不需要new
Math.PI 直接使用,不需要创建
console.log(Math.PI)//3.1415926
Math.max() / Math.min()
返回一组数字中的最大/小值,如果给定的参数中至少有一个参数无法转换为数字则返回NaN。
console.log(Math.max(10,22,5));//22
console.log(Math.max(10,'a',5));//NaN
console.log(Math.min(10,22,5));//5
console.log(Math.min(10,'a,5));//NaN
取整函数
Math.floor 向下取整
console.log(Math.floor(1.1));//1
console.log(Math.floor(1.5));//1
console.log(Math.floor(1.9));//1
console.log(Math.floor(-1.1));//-2
console.log(Math.floor(-1.5));//-2
console.log(Math.floor(-1.9));//-22、
Math.ceil向上取整
console.log(Math.ceil(1.1));//2
console.log(Math.ceil(1.5));//2
console.log(Math.ceil(1.9));//2
console.log(Math.ceil(-1.1));//-1
console.log(Math.ceil(-1.5));//-1
console.log(Math.ceil(-1.9));//-1
Math.round四舍五入 就近取整
console.log(Math.round(1.1));//1
console.log(Math.round(1.9));//2
console.log(Math.round(-1.1));//-1
console.log(Math.round(-1.9));//-2
//.5谁大取谁
console.log(Math.round(1.5));//2
console.log(Math.round(-1.5));//-1
Math.random生成随机数(重点)
返回的是0~1之间的随机小数 [0,1)
这个随机函数括号之间不写参数
console.log(Math.random());
得到一个两个数之间的随机整数,包括两个数在内的方法:
function getRandom(min,max){
return Math.floor(Math.random()*(max-min+1))+min;
}
console.log(getRandom(0,5));
案例:随机生成背景颜色
<style>
body {
background-color: rgb(0, 255, 0);
}
</style>
<script>
function getRandom(min,max){
return Math.floor(Math.random()*(max-min+1))+min;
}
console.log(getRandom(0,5));
function getRandomColor(){
var c1=getRandom(0,255);
var c2=getRandom(0,255);
var c3=getRandom(0,255);
return 'rgb(' + c1 + ',' + c2 + ',' + c3 + ')'
}
console.log(getRandomColor());
// 下面的代码演示写的程序没有错误
window.onload = function() {
document.body.style.backgroundColor = getRandomColor();
}
</script>
Math.abs()
alert(Math.abs(-1)); //1
alert(Math.abs('1'));//1 隐式转换 讲字符型转换为数值型 再取绝对值
alert(Math.abs('abs'));//NaN 如果里面参数 有非数字型的 字符串 返回的结果是 NaN