• JavaScript 学习18.Math数学运算 上海


    前言

    Math 对象允许您执行数学任务。
    Math 不是构造函数。Math 的所有属性/方法都可以通过使用 Math 作为对象来调用,而无需创建它

    Math 属性

    Math 提供了一些属性,可以快速得到一个数学里面的值,如圆周率π(约为3.14),2的平方根约1.414

    const x = Math.PI;            // 返回 PI
    const y = Math.SQRT2;      // 返回 2 的平方根
    console.log(x);
    console.log(y);
    

    Math 方法

    Math 对象一些常用的方法:

    • abs(x), 返回x的绝对值
    • max(x, y, z, ..., n) 返回最大值
    • min(x, y, z, ..., n) 返回值最小的数字。
    • pow(x, y) 返回 x 的 y 次幂值。
    • round() 返回数字四舍五入到最接近的整数。
    • floor(x) 返回向下舍入为最接近的整数。
    • random() 返回0到1直接随机数

    abs(x), 返回x的绝对值

    let x = 3;
    let y = -4;
    let a = Math.abs(x);
    let b = Math.abs(y);
    console.log(a, b)   // 3 4
    

    max(x, y, z, ..., n) 返回最大值

    let a = Math.max(2, 5);
    let b = Math.max(0, 2, 4, 7, 12);
    let c = Math.max(-2, 5);
    console.log(a);  // 5
    console.log(b);   // 12
    console.log(c);   // 5
    

    如何得到一个数组对象里面成员最大值和最小值?

    let x = [2, 4, 7, 12];
    console.log(Math.max(x));  // NaN
    console.log(Math.min(x));  // NaN
    

    如果 Math.max() 直接传数组对象,那么得到的结果是NaN.
    max()和min()方法需要传多个参数,而不是一个数组,所以可以用到扩展运算符(...)

    let x = [2, 4, 7, 12];
    console.log(Math.max(...x));  // 12
    console.log(Math.min(...x));  // 2
    

    pow(x, y) 返回 x 的 y 次幂

    let x = Math.pow(2, 3);  // 2的3次幂 8
    let y = Math.pow(2, 4);  // 2的3次幂 16
    console.log(x);
    console.log(y);
    

    指数运算还可以用到两个星号运算符**

    let x = 2**3;
    let y = 2**4;
    console.log(x);  // 8
    console.log(y);   // 16
    

    round() 返回数字四舍五入到最接近的整数。

    四舍五入取整

    let a = Math.round(2.60);   // 3
    let b = Math.round(2.50);   // 3
    let c = Math.round(2.49);   // 2
    let d = Math.round(-2.60);   // -3
    let e = Math.round(-2.50);  // -2
    let f = Math.round(-2.49);  // -2
    

    floor(x) 返回向下舍入为最接近的整数。

    向下舍入取整

    let a = Math.floor(0.60);   // 0
    let b = Math.floor(0.40);   // 0
    let c = Math.floor(5);    // 5
    let d = Math.floor(5.1);   // 5
    let e = Math.floor(-5.1);   // -6
    let f = Math.floor(-5.9);    // -6
    

    random() 返回随机数

    random() 方法返回从 0(含)到 1(不含)的随机数。

    let x = Math.random();
    let y = Math.random();
    console.log(x);  // 0.041820330842348596
    console.log(y);  // 0.8178949610470638
    

    返回 1 到 10 之间的随机整数:

    let x = Math.floor((Math.random() * 10) + 1);
    console.log(x); // 5
    

    返回 1 到 100 之间的随机整数:

    let x = Math.floor((Math.random() * 100) + 1);
    console.log(x); // 80
    
  • 相关阅读:
    阿里云服务器Linux CentOS安装配置(五)jetty配置、部署
    阿里云服务器Linux CentOS安装配置(四)yum安装tomcat
    阿里云服务器Linux CentOS安装配置(三)yum安装mysql
    阿里云服务器Linux CentOS安装配置(二)yum安装svn
    【搭建git+maven+jenkins持续集成环境】[一] 搭建git服务器
    使用nginx的反向代理后play获取不到客户端的ip的问题
    MyBatis Generator配置文件翻译
    MyBatis -generator应用
    编程之术与道
    java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/16300211.html
Copyright © 2020-2023  润新知