js Math对象的常用方法

版权声明:本文为博主原创文章,转载请注明出处 thx~ https://blog.csdn.net/x550392236/article/details/88943354

Math 对象

Math 对象用于执行数学任务。属于对象数据类型 typeof Math => ‘object’
Math 对象并不像 Date 和 String 那样是对象的类,因此没有构造函数 Math(),像 Math.sin() 这样的函数只是函数,不是某个对象的方法。无需创建它,通过把 Math 作为对象使用就可以调用其所有属性和方法。


Math.abs() 获取绝对值

Math.abs(-12); // 12
Math.abs(-0); // 0

Math.ceil() 向上取整
Math.floor() 向下取整

Math.ceil(3.14) ; // 4
Math.floor(3.14); // 3 

Math.round() 四舍五入

Math.round(16.45); // 16
Math.round(16.54); // 17

Math.random() 取[0,1)的随机小数

Math.random(); // 0-1 随机小数 
Math.random()*10; // 0-10 随机小数 
Math.round(Math.random()*10); // 0-10 随机整数 
// 获取[n,m]之间的随机整数
Math.round(Math.random()*(m-n)+n);
Math.round(Math.random()*(9-3)+3); // 3-9 随机整数

Math.max() 获取一组数据中的最大值
Max.min() 获取一组数据中的最小值

Math.max(-1,0,1,2,3); // 3
Math.max(...[-1,0,1,2,3]); // 3
Math.max.apply(null, [-1,0,1,2,3]); // 3

Math.min(-1,0,1,2,3); // -1
Math.min(...[-1,0,1,2,3]); // -1
Math.min.apply(null, [-1,0,1,2,3]); // -1

Math.pow()获取一个值的多少次幂
Math.sqrt()对数值开方

Math.pow(3,2); // 9  3的2次方
Math.sqrt(9); // 3  9的开方

Math.PI 获取圆周率π 的值

Math.PI; // 3.141592653589793

猜你喜欢

转载自blog.csdn.net/x550392236/article/details/88943354