导航菜单
  • 首页
  • 首页>前端万博manbext备用网址>JavaScript万博manbext备用网址

    JavaScript基础8:Math及常用方法

    Math和Array一样,算是JavaScript的一种内置对象,自带了很多的函数可以处理数字方面的任务。

    Math也有属性和方法。与其他全局对象不同,数学对象没有构造函数。方法和属性是静态的。所有方法和属性(常量)都可以在不首先创建Math对象的情况下使用。也就是不需要new一个对象的实例。

    一、常用的属性

    估计也只有这个Math.PI (π)属性会被用到了。

    Math.PI;//3.141592653589793

    二、常用的方法

    这个还是挺多的。

    1、Math.pow(x,y)

    y是x的幂数。

    Math.pow(2,6);//64

    2、Math.sqrt(x)

    返回x的平方根。

    Math.sqrt(4);//2

    3、Math.abs(x)

    返回x的绝对值。

    Math.abs(-12.5);// 12.5

    4、Math.min(x,y,...,n)

    取最小值。

    Math.min(1,5-20,-12.5,12.78);//-15

    5、Math.max(x,y,...,n)

    取最大值。

    Math.max(12,20,7+20,5-12); // 27

    6、Math.round()

    round是"附近,周围"的意思,round and round,绕圈圈。所以这个函数是取离得近的整数。

    不过正负是有点差别的。

    Math.round(12.68);// 13
    Math.round(-12.68);// -13
    
    Math.round(11.5);// 12
    Math.round(-11.5);//-11
    
    Math.round(10.45);// 10
    Math.round(-10.45);//-10

    总结:(小数点后第一位)大于五全部加,等于五正数加,小于五全不加。

    7、Math.floor()

    floor是“地板”的意思,意思是找接近的最小整数。

    Math.floor(11.45)=Math.floor(11.78)=Math.floor(11.5)=11;
    Math.floor(-11.45)=Math.floor(-11.78)=Math.floor(-11.5)=-12;

    8、Math.ceil()

    ceil是“天花板”的意思,那就找接近的最大整数。

    Math.ceil(11.45)=Math.ceil(11.78)=Math.ceil(11.5)=12;
    Math.ceil(-11.45)=Math.ceil(-11.78)=Math.ceil(-11.5)=-11;

    9、Math.random()

    随机数。返回0-1,但是不包括1的随机小数。

    Math.random();// 随机变化的小数,比如 0.7285024347724851

    通过乘以10的倍数,再结合Math.floor可以得到一定范围的随机整数。

    Math.floor(Math.random()*10);// 0-9的随机整数
    Math.floor(Math.random()*100);// 0-99的随机整数
    Math.floor(Math.random()*50+1);//1-50的随机整数

    可以创建两个函数来获得随机整数。

    不包括最大值的函数:

    function getRandomInt(min, max){
        min=Math.ceil(min);
        max=Math.floor(max);
        return Math.floor(Math.random()*(max - min))+min;     
    }
    getRandomInt(12.5,18.5); //13-17之间的随机整数。

    包括最大值的函数:

    function getRandomIntInc(min, max){
        min=Math.ceil(min);
        max=Math.floor(max);
        return Math.floor(Math.random()*(max - min + 1))+min;     
    }
    getRandomIntInc(12.5,20.8);// 13-20之间的随机整数

    点赞


    2
    保存到:

    相关文章

    发表评论:

    ◎请发表你卖萌撒娇或一针见血的评论,严禁小广告。

    Top