ES6数值Math

Math.trunc()----用于去除一个数的小数部分,返回整数部分

Math.trunc(5.1)  //5
Math.trunc(5.9)  //5
Math.trunc(-5.1)  //-5
Math.trunc(-5.9)  //-5
Math.trunc(-0.123456)  //0
//非数值==》》数值
Math.trunc('123.456')  //123
Math.trunc(true) //1
Math.trunc(false) //0
Math.trunc(null) //0
//空值和无法截取整数的值,返回NaN
Math.trunc(NaN)//NaN
Math.trunc()  //NaN

对于没有部署这个方法的环境,可以用下面的代码模拟

Math.trunc = Math.trunc || function(x){
    return x < 0 ? Math.ceil(x):Math.floor(x);
}

Math.sign()----判断一个数是正数、负数、或零。非数值先转换为数值

返回 5 种值

    -参数为正数,返回+1

    -参数为负数,返回-1

    -参数为 0 ,返回0

    -参数为-0,返回-0

    -其他值,返回NaN

对于没有部署这个方法的环境,可以用下面的代码模拟

Math.sign = Math.sign || function(x){
    x = +x;//convert to a number
    if(x ===0 || isNaN(x)){
        return x;
    }
    return x > 0 ?1:-1;
};

Math.cbrt()----计算一个数的立方根

Math.cbrt('8')  //2

代码模拟

Math .cbrt = Math.cbrt || function(x){
    var y=Math.pow(Math.abs(x),1/3);
    return x<0?-y:y;
}
Math.clz32()----JavaScript的整数使用32位二进制形式表示,Math.clz32方法返回一个数的32位无符号整数形式有多少个前导0



猜你喜欢

转载自blog.csdn.net/dongjing0813/article/details/80758346