javascript之Math对象

112 阅读1分钟

概念

Math对象包含了数学相关的操作和方法,其所有的属性都需要通过类名来调用

常用方法

Math.floor(num);

功能:向下取整

Math.floor(-2.3);    //-3
Math.floor(2.6);     //2

Math.ceil(num);

功能:向上取整

Math.floor(-2.3);     //-2

Math.round(num);

功能:四舍五入取整

Math.round(4.5);   //5

Math.abs(num);

功能:返回绝对值

Math.abs(-1);   //1

Math.sqrt(num);

功能:开平方根

Math.sqrt(9);     //3

Math.pow(m,n);

功能:返回m的n次方

Math.pow(2,3);  //8

Math.min(num,...num);

功能:返回多个数中的最小值

Math.min(2, 3, 5, 21, 7, 1, 4, 6);  //1

//通过apply改变this指向获取数组中的最小值:
Math.min.apply(null,[5, 21, 7, 1, 4]);   //1

Math.max(num,...num);

功能:返回多个数中的最大值

Math.max(2, 3, 5, 21, 7, 1, 4, 6);  //21

//通过apply改变this指向获取数组中的最大值:
Math.min.apply(null,[5, 21, 7, 1, 4]);  //21

Math.random();

功能:返回[0,1)之间的随机数

  • Math.round(Math.random()*10);----生成[0,10]之间的随机数
  • Math.round(Math.random()*max-min)+min;----生成[min,max]之间的随机数
Math.random();  //0.3042217805841394
Math.round(Math.random()*10);  //2
Math.round(Math.random()*8)+2;

//生成随机颜色
function getColor() {
    let color = '#', str = '0123456789abcdef';
    for (let j = 0; j < 6; j++) {
        color += str.charAt(Math.round(Math.random() * (str.length - 1)));
    }
    return color;
}

Math.sign(num);

功能:判断一个数到底是正数、负数、还是零。对于非数值,会先将其转换为数值。

  • 参数为正数,返回+1;
  • 参数为负数,返回-1;
  • 参数为 0,返回0;
  • 参数为-0,返回-0;
  • 其他值,返回NaN。
Math.sign(-5)  // -1
Math.sign(5)  // +1
Math.sign(0)  // +0
Math.sign(-0)  // -0
Math.sign(NaN)  // NaN