美文网首页
js的Math 对象

js的Math 对象

作者: 扶得一人醉如苏沐晨 | 来源:发表于2023-10-21 11:36 被阅读0次

    一、说明

    Math 和其他的对象不同,它不是一个构造函数

    它属于一个工具类不用创建对象,它里边封装了数学运算相关的属性和方法

    比如 Math.PI 表示的圆周率

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

    二、方法

    2.1. abs() 绝对值

    可以用来加算一个数的绝对值

    console.log(Math.abs(-1)); //1
    

    2.2. Math.ceil() 上取整

    可以对一个数向上取整,小数位只要有值就自动进 1

    console.log(Math.ceil(1.1)); //2
    

    2.3. Math.floor() 下取整

    可以对一个数进行向下取整,小数部分会被舍掉

    console.log(Math.floor(1.99)); //1
    

    2.3. Math.round() 四舍五入取整

    可以对一个数进行四舍五入取整

    console.log(Math.round(1.6)); //2
    

    2.5. Math.random()

    可以用来生成一个 0-1 之间的随机数

    2.5.1. 生成一个 0-10 的随机整数

    Math.round(Math.random() * 10);
    

    2.5.2. 生成 0-x 之间的随机整数

    Math.round(Math.random() * x);
    

    2.5.3. 生成一个 1-10随机整数

    Math.round(Math.random() * 9) + 1;
    

    2.5.4. 生成一个 x-y 之间的随机整数

    Math.round(Math.random()*(y-x)+x)
    

    2.6. max 和 min 最大值最小值

    max() 可以获取多个数种的最大值
    min() 可以获取多个数中的最小值

    var max = Math.max(10, 45, 30, 100);
    var min = Math.min(10, 45, 30, 100);
    console.log(max); //100
    console.log(min); //10
    

    2.7. Math.pow(x,y) 乘方

    返回 x 的 y 次幂

    console.log(Math.pow(12, 3)); //1728
    

    2.8. Math.sqrt() [开方] (平方根)(https://so.csdn.net/so/search?q=%E5%BC%80%E6%96%B9&spm=1001.2101.3001.7020)

    用于对一个数进行开方运算

    console.log(Math.sqrt(2));  //1.4142135623730951
    

    相关文章

      网友评论

          本文标题:js的Math 对象

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