js中的Math

js中的Math

Math.round 取最接近的整数   
    Math.round(-2.7) // -3

Math.ceil 向上取整
    Math.ceil(1.1) // 2

Math.floor 向下取整
    Math.floor(1.9) // 1

Math.trunc 取整
    Math.trunc(1111.111) // 1111

Math.sin 接受的参数是弧度
    弧度r和角度g的关系
    r = g*Math.PI/180
    Math.sin(30*Math.PI/180)

Math.cos
    Math.cos(60*Math.PI/180)

Math.sqrt 开平方
    Math.sqrt(4)

Math.cbrt 开三次方
    Math.cbrt(8)

Math.pow 次方
    Math.pow(10,10)         // 10000000000
    10 ** 10                // es7的写法
    Math.pow(16,1 / 4)      // 开四次方

Math.random 随机数
    Math.random()                       // [0,1)之间的随机数
    Math.random() * (20 - 10) + 10      // [10,20)之间的随机数
    Math.random() * (20 - 10 + 1) + 10  // [10,20]之间的随机数
    
Math.max 取最大值
    Math.max(...[2,1,5,0,2])
    Math.max.apply(Math, [2,1,5,0,2])
 
Math.min 取最小值
    Math.min(...[2,1,5,0,2])
    Math.min.apply(Math, [2,1,5,0,2])

Math.atan2 
    取原点到任意点的弧度
        var vector = {x: Math.sqrt(3), y: 1};
        var dir = Math.atan2(vector.y, vector.x);
        console.log(dir*180/Math.PI); // 30

    取任意两点连成的直线的弧度
        var line = {
            p1: {x: -Math.sqrt(3), y: 0},
            p2: {x: 0, y: 1}
        }
        var dir = Math.atan2(line.p2.y - line.p1.y, line.p2.x- line.p1.x);
        console.log(dir*180/Math.PI); // 30

Math.hypot 取n个值的平方和根
    var p1 = {x: 1, y: 2};
    var p2 = {x: 3, y: 4};
    var dis = Math.hypot(p2.x-p1.x, p2.y-p1.y); // 取两点间的距离

猜你喜欢

转载自www.cnblogs.com/ye-hcj/p/10349826.html
今日推荐