math方法
不能把math当作函数进行调用,math只是一个对象,提供了一些和数学操作相关的属性和方法。
1、圆周率
console.log(Math.PI);
output: 3.1415926.......
2、ceil 向上取整
得到一个比当前值大的整数或者和当前一样的数值
var num = 1.0002;
console.log(Math.ceil(num));
output: 2
3、floor 向下取整
得到一个比当前值小的整数或者和当前一样的数值
var num = 1.9;
console.log(Math.floor(num));
output:1
4、round 四舍五入
var num = 1.5;
console.log(Math.round(num));
output: 2
5、random 随机数
得到一个随机数,这个数字是0~1之间的值,包含0但是不包含1
取0~n之间的随机数 Math.random() * n
取m~n之间的随机数 Math.random() * (n-m) + n
随机数取整配合ceil floor round 使用
function getNum(min,max){
return Math.round(Math.random() * (max - min) + min);
}
var a = getNum(2,17);
6、Math.max()与Math.min()
Math.max() 返回是当前一数组中的最大值,如果不给参数,返回-Infinity
console.log(Math.max(10,34,15,28,78));
output: 78
Math.min() 返回是当前一数组中的最小值,如果不给参数,返回Infinity
console.log(Math.min(11,34,15,28,78));
output: 11
以上两个方法,在内部都会执行Number,如果是不可以转成有效值,会返回NaN
5、abs 绝对值
var num = 2-17;
console.log(Math.abs(num));
output: 15