JS Math 对象常用方法 ES5

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>

<body>
  <script>
    // 1. abs() 方法 可返回一个数的绝对值。
    let num1 = -3.14
    let r1 = Math.abs(num1)
    console.log("TCL: r1", r1) // TCL: r1 3.14

    // 2. ceil() 方法
    // ceil() 方法可对一个数进行上舍入。
    // 如果参数是一个整数,该值不变。
    // 注意:ceil() 方法执行的是向上取整计算,它返回的是大于或等于函数参数,并且与之最接近的整数。
    let num2 = 3.14
    let r2 = Math.ceil(num2)
    console.log("TCL: r2", r2) // TCL: r2 4

    // 3.  floor() 方法
    // floor() 方法返回小于等于x的最大整数。
    // 如果传递的参数是一个整数,该值不变。
    let num3 = 3.14
    let r3 = Math.floor(num3)
    console.log("TCL: r3", r3) // TCL: r3 3

    // 4. max() 方法
    // max() 方法可返回两个指定的数中带有较大的值的那个数。
    let r4 = Math.max(5, 10, 9)
    console.log("TCL: r4", r4) // TCL: r4 10

    // 5. min() 方法
    // min() 方法可返回指定的数字中带有最小值的数字。
    let r5 = Math.min(5, 10, 9)
    console.log("TCL: r5", r5) // TCL: r5 5

    // 6. pow() 方法
    // pow() 方法返回 x 的 y 次幂
    let r6 = Math.pow(2, 3) // 2 的 3 次幂
    console.log("TCL: r6", r6) // TCL: r6 8

    // 7. random() 方法
    // random() 方法可返回介于 0(包含) ~ 1(不包含) 之间的一个随机数。
    let r7 = Math.random()
    console.log("TCL: r7", r7) // TCL: r7 0.033367716904862954
    // 以下函数返回 min(包含)~ max(不包含)之间的数字:
    function getRndInteger(min, max) {
      return Math.floor(Math.random() * (max - min)) + min
    }
    let r7_1 = getRndInteger(1, 10) // 返回 1(包含)~ 10(不包含)之间的数字
    console.log("TCL: r7_1", r7_1) // TCL: r7_1 3

    // 8.  round() 方法
    // round() 方法可把一个数字舍入为最接近的整数
    // 注意: 2.49 将舍入2 , 2.5 将舍入 3
    let sum8 = 2.3
    let r8 = Math.round(sum8)
    console.log("TCL: r8", r8) // TCL: r8 2

    // 9.  sqrt() 方法
    // sqrt() 方法可返回一个数的平方根
    let sum9 = 9
    let r9 = Math.sqrt(sum9)
    console.log("TCL: r9", r9) // TCL: r9 3

  </script>
</body>

</html>
发布了171 篇原创文章 · 获赞 499 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_43258252/article/details/101693585
今日推荐