美文网首页
Math常用方法

Math常用方法

作者: Artifacts | 来源:发表于2019-09-15 16:17 被阅读0次
    // math叫数学函数,但却是一个对象,存储了许多操作数字的方法
    console.log(typeof Math);//=>"object"
    console.dir(Math);
    /*
     * Math = {
         PI:3.1415926..,
         abs:function(){[native code]},
         ceil:function(){[native code]},//向上舍入
         ...
     *}
     * 
     *Math.abs();
     *Math.PI;
     */
    

    Math中常用的属性和方法

    1.Math.abs([number value])
    获取绝对值(绝对值永远是正数或者零)

    // 传递的不是数字类型的值:先基于Number()转换为数字再处理
    console.log(Math.abs('-1'));//=>1
    console.log(Math.abs('-1px'));//=>NaN
    console.log(Math.abs(true));//=>1
    

    2.Math.ceil/floor([Number value])
    把一个数向上取整/向下取整

    console.log(Math.ceil(-12.9));//=>-12
    console.log(Math.floor(-12.1));//=>-13
    

    3.Math.round()
    四舍五入

    console.log(Math.round(12.5));//=>13  正数中.5属于入
    console.log(Math.round(-12.5));//=>-12 负数中.5属于舍
    

    4.Math.max/min([val1],[val2],...)
    获取一堆数中的最大值和最小值

    Math.max([12,3,4,67]);//=>NaN 此处是只传递一个值,是个数组,和内置语法不一样
    

    5.Math.sqrt/pow()
    sqrt:给一个数开平方
    pow:计算一个数的多少次幂

    console.log(Math.sqrt(-9));//=>NaN 负数无法开平方
    console.log(Math.pow(2,10));//=>1024 
    

    6.Math.random()
    获取0-1之间的随机小数

    for (let i=1;i<10;i++){
        console.log(Math.random());
    }
    
    //获取[1-10]之间的随机整数
    Math.round(Math.random()*9+1);
    //获取[n-m]之间的随机整数
    包含n也包含m,n<m
    Math.round(Math.random()*(m-n)+n);
    

    相关文章

      网友评论

          本文标题:Math常用方法

          本文链接:https://www.haomeiwen.com/subject/prouyctx.html