Math对象
在这里主要是整理了一些常用的Math方法,具体的可以查阅MDN文档,上面有很多方法。Math数学对象不是一个构造函数,所以我们不需要new来调用,而是直接使用里面的属性和方法即可。
1.Math.PI(圆周率)
console.log(Math.PI);//3.141592653589793
2.Math.floor() (向下取整,往最小了取值)
console.log(Math.floor(1.1));//1
console.log(Math.floor(1.9));//1
3.Math.ceil() (向上取整,往最大了取值)
console.log(Math.ceil(1.1));//2
console.log(Math.ceil(1.9));//2
4.Math.round() (四舍五入,但是.5特殊,是往大了取值)
console.log(Math.round(1.4));//1
console.log(Math.round(1.5));//2
console.log(Math.round(-1.5));//-1
console.log(Math.round(-1.4));//-1
console.log(Math.round(-1.6));//-1
5.Math.abs() (绝对值)
console.log(Math.abs(-1.11));//1.11
6.Math.max()和Math.min() (最大值和最小值)
console.log(Math.max(10,1,9,100,200,45,78)); // 200
console.log(Math.min(10,1,9,100,200,45,78)); // 1
7.Math.random() (求随机数,返回的是从0到小于1的一个随机小数)
(1)得到一个两数之间的随机整数,包含最小值,不包含最大值
function getRandom(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值
}
console.log(getRandom(1,10));
(2)得到一个两数之间的随机整数,包含两数在内
function getRandom(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
console.log(getRandom(1, 10));