Math
对象并不像 Date
和 String 那样是对象的类,因此没有构造函数 Math()
,像Math.sin()
这样的函数只是函数,不是某个对象的方法。您无需创建它,通过把 Math
作为对象使用就可以调用其所有属性和方法。
当你要使用某一个方法的时候,只需要打上Math
前缀,再调用其下的属性或方法即可。
<script> ? "use strict"; ? console.log(Math.pow(3,3)); // 直接打上Math前缀,然后点出方法或属性。 ? </script>
属性 | 描述 |
---|---|
返回算术常量 e,即自然对数的底数(约等于2.718)。 | |
返回 2 的自然对数(约等于0.693)。 | |
返回 10 的自然对数(约等于2.302)。 | |
返回以 2 为底的 e 的对数(约等于 1.414)。 | |
返回以 10 为底的 e 的对数(约等于0.434)。 | |
返回圆周率(约等于3.14159)。 | |
返回返回 2 的平方根的倒数(约等于 0.707)。 | |
返回 2 的平方根(约等于 1.414)。 |
方法 | 描述 |
---|---|
返回数的绝对值。 | |
返回数的反余弦值。 | |
返回数的反正弦值。 | |
以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值。 | |
返回从 x 轴到点 (x,y) 的角度(介于 -PI/2 与 PI/2 弧度之间)。 | |
对数进行上舍入。 | |
返回数的余弦。 | |
返回 e 的指数。 | |
对数进行下舍入。 | |
返回数的自然对数(底为e)。 | |
返回 x 和 y 中的最高值。 | |
返回 x 和 y 中的最低值。 | |
返回 x 的 y 次幂。 | |
返回 0 ~ 1 之间的随机数。 | |
把数四舍五入为最接近的整数。 | |
返回数的正弦。 | |
返回数的平方根。 | |
返回角的正切。 | |
返回该对象的源代码。 | |
返回 Math 对象的原始值。 |
取最大值。
<script> ? "use strict"; ? let max_value = Math.max(2,1000,500,2.14); console.log(max_value); // 1000 ? </script>
取最小值。
<script> ? "use strict"; ? let max_value = Math.min(2,1000,500,2.14); console.log(max_value); // 2 ? </script>
从数组中取出值。
<script> ? "use strict"; ? let min_value = Math.min.apply(Math,[1,2,3,4,5]); console.log(min_value); // 1 ? </script>
向上取整。
<script> ? "use strict"; ? let value = Math.ceil(54.1); console.log(value); // 55 ? </script>
向下取整。
<script> ? "use strict"; ? let value = Math.floor(54.1); console.log(value); // 54 ? </script>
四舍五入。
<script> ? "use strict"; ? console.log(Math.round(54.4)); // 54 console.log(Math.round(54.5)); // 55 ? </script>
返回次幂。
<script> ? "use strict"; ? console.log(Math.pow(3,3)); // 27 3*3*3 ? </script>
随机生成大于0小于1之间的浮点数。
<script> ? "use strict"; ? console.log(Math.random()); // 0.5178539433566185 ? </script>
随机生成大于0小于5之间的浮点数。
<script> ? "use strict"; ? console.log(Math.random()*5); // 4.448636644785453 ? </script>
下面取2~5的随机数(整数,不包括5)公式为:min+Math.floor(Math.random()*(Max-min))
<script> ? "use strict"; ? const number = Math.floor(Math.random() * (5 - 2)) + 2; console.log(number); // 4 ? </script>
下面取2~5的随机数(整数,包括5)公式为:min+Math.floor(Math.random()*(Max-min+1))
<script> ? "use strict"; ? const number = Math.floor(Math.random() * (5 - 2 + 1)) + 2; console.log(number); // 3 ? </script>
从数组中取出一个随机元素
<script> ? "use strict"; ? let array = ["v1", "v2", "v3", "v4"] ? const index = Math.floor(Math.random() * array.length); const val = array[index]; console.log(val); // v3 ? </script> ?
从数组中随机取出索引1
到3
之间的元素。
<script> ? "use strict"; ? let array = ["v1", "v2", "v3", "v4"] ? const index = Math.floor(Math.random() * (5 - 2)) + 1; const val = array[index]; ? console.log(val); // v3 ? </script>
原文:https://www.cnblogs.com/Yunya-Cnblogs/p/13388808.html