js中Math对象常用的属性和方法

1 Math对象

1.1定义:Math是js的一个内置对象,它提供了一些数学方法.

1.2特性:不能用构造函数的方式创建,无法初始化,只有静态属性和方法

1.3静态属性

1.3.1 Math.PI 圆周率 π=3.1415926...

1.4静态方法

1.4.1 Math.sin(x) 正弦值

参数:弧度 x=Math.PI/180*deg

1.4.2 Math.cos(x) 余弦值

1.4.3 Math.tan(x) 正切值

1.4.4 Math.random() 返回0~1间随机数

参数:无
返回值:返回0~1之间的随机数,包含0,不包含1,范围[0,1)
示例:

Math.random(); //  0.8982374747283757
Math.random(); //  0.39617531932890415

1.4.5 Math.round(value) 四舍五入取整

参数:数字或纯数字的字符串
返回值:整数,若参数错误,返回NaN
四舍五入取整:实质上取的是最靠近的值;且无论正数负数,进位的值是相邻的正无穷方向上的数
换种方法理解,正数中,舍去的"四"是较小的值,范围是(0,0.5) ;进位的"五"是较大的值,范围是[0.5,1);
负数中,舍去的"四"同样是较小的值,但范围变为(-1,-0.5) ;进位的"五"是较大的值,范围是(0,-0.5];
示例:

Math.round(2.2);    //2 取最靠近2.2的值2
Math.round(2.8);    //3
Math.round(-2.2);   //-2
Math.round(-2.8);   //-3
Math.round(2.5);    //3 小数为0.5,向正无穷方向进位
Math.round(-2.5)   //-2

因为random方法的特性:取得到最小值,取不到最大值,可以用Math.round()来取整,以获取一个任意区间的随机数

function random1(max,min){
    return Math.round(Math.random()*(max-min)+min)
}   
     // 上下二式等价
function random2(max,min){
     // Math.floor是向下取整,范围要加1;也可换为parseInt方法
    return Math.floor(Math.random()*(max-min+1)+min)        
}

1.4.6 Math.floor(value) 向下取整

参数:数字或纯数字的字符串
返回值:整数,若参数错误,返回NaN
示例:

Math.floor( 66.6);   //66
Math.floor(-66.6);   //-67

1.4.7 Math.ceil(value) 向上取整

参数:数字或纯数字的字符串
返回值:整数,若参数错误,返回NaN
示例:

Math.ceil( 66.6);   //67
Math.ceil(-66.6);   //-66

1.4.8 Math.max(n1,n2,n3,n...) 最大值

参数:多个参数,数字或纯数字的字符串
返回值:最大值,若参数错误,返回NaN
示例:

//求数组中的最大项
var arr=[10,20,30,40,50]
Math.max(10, 20,30,40,50); 
Math.max.bind(object,10,20,30,40,50);
Math.max.apply(object,arr)
  • 推荐用apply方法,它接收两个参数,参数1是为this指定的对象,参数2是数组;
  • 数组比较长时不用手动输入各项参数,比较方便

1.4.9 Math.min(n1,n2,n3,n...) 最小值

参数:多个参数,数字或纯数字的字符串
返回值:最小值,若参数错误,返回NaN

1.4.10 Math.abs(value) 绝对值

参数:数字或纯数字的字符串
返回值:绝对值,若参数错误:非数字字符串、undefined、空,返回NaN;
参数为null返回0
示例:

Math.abs("abc");         // NaN
Math.abs(undefined); // NaN
Math.abs();                // NaN
Math.abs(null);          // 0

1.4.11 Math.pow(x,y) x的y次方

参数:两个参数,数字或纯数字的字符串
返回值:x的y次方,若参数错误,返回NaN
示例:

Math.pow("3",2)   //9
Math.pow(2,3)     //8

1.4.12 Math.sqrt(value) 平方根

参数:数字或纯数字的字符串
返回值:平方根,若参数为负数,返回NaN
示例:

Math.sqrt("2");  // 1.414213562373095
Math.sqrt(0);   // 0
Math.sqrt(-1);  // NaN