Math对象
Math对象属于Javascript内置对象,无需实例化(不需要添加new ),可以直接使用
属性
Math.PI
方法
1. Math.round(number) //四舍五入整数
2. Math.ceil(number) //向上取整
3. Math.floor(number) //向下取整
4. Math.random() //随机返回0.0~1.0之间的数
5. Math.max(x,y) //求最大值
6. Math.min(x,y) //求最小值
7. Math.pow(x,y) //求xy
console.log(Math.PI); // PI
console.log(Math.round(8.5)); // 四舍五入
console.log(Math.abs(-10)); // 四舍五入
console.log(Math.round(6.4));
console.log(Math.ceil(6.4)); // 向上取整
console.log(Math.floor(6.9)); // 向下取整
console.log(Math.max(1,7,6,4,9,2)); // 最大值
console.log(Math.min(1,7,6,4,9,2)); // 最小值
console.log(Math.pow(5,8)); // 求x的y次方
// 随机数 0-1
console.log(Math.random());
// 随机数 0-9
console.log(Math.floor(Math.random()*10));
// 随机数 0-99
console.log(Math.floor(Math.random()*100));
// 随机数 1-10
console.log(Math.floor(Math.random()*10)+1);
// 随机数 5-10
console.log(Math.floor(Math.random()*6)+5);
// 随机数 7-18
console.log(Math.floor(Math.random()*12)+7);
// 随机数公式:Math.floor(Math.random()*(max-min+1))+minMath.floor(Math.random()*(max-min+1))+min
案例:Math数学相关案例
- 获取指定范围的随机数
Math.floor(Math.random()*(max-min+1))+min
- 封装一个获取指定范围的随机数
3
封装一个获取随机颜色的功能
function randColor(){
// 将获取到的三个随机颜色,拼接在rgb颜色值中
return 'rgb('+getRand(0,255)+','+getRand(0,255)+','+getRand(0,255)+')';
}
Global对象
Global对象是ECMAscript中最特别的对象,因为它根本不存在。说它不存在是因为在ECMAscript中,不存在独立的函数,所有函数都必须是某个对象的方法。
例如isNaN(),isFinite(),parseInt()和parseFloat()等,都是Global对象的方法