不知道js中的数学函数Math你就太low了

5次阅读

共计 988 个字符,预计需要花费 3 分钟才能阅读完成。

js 中的数学函数 Math

Math 称为数学函数,但是它属于对象类型

   typeof Math => "object"
  

Math 为数学函数,提供了很多操作数字的方法

Math 常用方法

abs
取绝对值

  Math.abs(-10)
=>10

ceil/floor
向上或者向下取整

  Math.ceil(12.444)
=>13  // 向上
Math.ceil(-12.444)
=>-12
Math.floor(-12.444)
=>-13  // 向下
Math.floor(12.444)
=>12

round
四舍五入

  Math.round(-10.5)
=>10

sqrt
开平方

  Math.sqrt(100)
=>10

pow
取幂 (n 的 m 次方) Math.pow(n,m)

 Math.pow(2,10)
=>1024

max/min
获取最大值和最小值

    Math.max(12,23,34,45,56)
=>56
   Math.min(12,23,34,45,56)
=>12

PI
获取圆周率

 Math.PI
=>3.141592653589793

random
获取 0 - 1 之间的随机小数

for (var i=0;i<10;i++){console.log(Math.random());
}
=>
VM546:2 0.04970057257337013
VM546:2 0.6231351064275747
VM546:2 0.5078224023964912
VM546:2 0.8352905252558647
VM546:2 0.6559457705463638
VM546:2 0.8613184309923703
VM546:2 0.560912961148593
VM546:2 0.007279315129435915
VM546:2 0.8116470880389592
VM546:2 0.7306956598107344
undefined

思考:1-10 之间的整数
Math.round(Math.random()*(m-n)+n):获取 n - m 之间的随机整数

   for (var i=0;i<10;i++){console.log(Math.round(Math.random()*(69-24)+24));
}
=> VM675:2 58
VM675:2 34
VM675:2 64
VM675:2 38
VM675:2 34
VM675:2 36
VM675:2 33
VM675:2 61
VM675:2 33
VM675:2 55
undefined
正文完
 0