美文网首页
Math 对象

Math 对象

作者: 樱桃小白菜 | 来源:发表于2021-06-17 18:43 被阅读0次

    Math 对象

    Math 对象用于执行数学任务

    Math 对象并不像 Date 和 String 那样是对象的类,因此没有构造函数 Math()

    常用的 Math () 方法

    常用的取整方法

    ceil()

    Math.ceil() 方法可对一个数进行上舍入

    var num = 0.4
    Math.ceil(num)
    
    console.log(num,Math.ceil(0.4))  //1
    

    floor()

    Math.floor() 方法可以向下取整

    console.log(Math.floor(0.4))  //0
    

    round()

    Math.round() 方法可以四舍五入取整

    console.log(Math.round(0.4))  //0
    

    常用方法

    abs()

    Math.abs() 方法可以返回绝对值

    console.log(Math.abs(-0.4))  //0.4
    

    random()

    Math.random() 方法可以返回一个 0 - 1 的随机数

    console.log(Math.round(Math.random()*10))
    //0-10的随机数
    

    PI

    Math.PI 方法可以返回绝对值

    console.log(Math.PI))  //3.141592653589793
    

    max()

    Math.max() 函数返回一组数中的最大值。

    console.log(Math.max(1, 3, 2));
    // expected output: 3
    
    console.log(Math.max(-1, -3, -2));
    // expected output: -1
    
    const array1 = [1, 3, 2];
    
    console.log(Math.max(...array1));
    // expected output: 3
    

    min()

    Math.min() 返回零个或更多个数值的最小值。

    console.log(Math.max(1, 3, 2));
    // expected output: 1
    
    console.log(Math.max(-1, -3, -2));
    // expected output: -3
    
    const array1 = [1, 3, 2];
    
    console.log(Math.max(...array1));
    // expected output: 1
    

    使用 Math.min() 裁剪值

    var x = Math.min(f(foo), boundary);
    // 等同于
    // var x = f(foo);
    // if (x > boundary) {
    //     x = boundary;
    // }
    

    相关文章

      网友评论

          本文标题:Math 对象

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