首页 > 其他分享 >JS——Math(数学&随机方法)

JS——Math(数学&随机方法)

时间:2022-12-09 16:13:44浏览次数:53  
标签:返回 10 min floor random JS 随机 Math

Math 对象方法

  • 与其他全局对象不同,Math对象没有构造函数。方法和属性是静态的
  • 可以在不首先创建Math对象的情况下使用所有方法和属性(常量)
方法 描述
abs(x) 返回 x 的绝对值。
acos(x) 返回 x 的反余弦值,以弧度为单位。
acosh(x) 返回 x 的双曲反余弦值。
asin(x) 返回 x 的反正弦值,以弧度为单位。
asinh(x) 返回 x 的双曲反正弦值。
atan(x) 返回 x 的反正切值,返回的值是 -PI/2 到 PI/2 之间的弧度值。
atan2(yx) 返回其参数商的反正切值。
atanh(x) 返回 x 的双曲反正切值。
cbrt(x) 返回 x 的三次方根。
ceil(x) 返回 x,向上舍入为最接近的整数。
clz32(x) 返回 x 的 32 位二进制表示中前导零的数量。
cos(x) 返回 x 的余弦值(x 以弧度为单位)。
cosh(x) 返回 x 的双曲余弦值。
exp(x) 返回 Ex 的值。
expm1(x) 返回 Ex 减去 1 的值。
floor(x) 返回 x,向下舍入为最接近的整数。
fround(x) 返回数的最接近的(32 位单精度)浮点表示。
log(x) 返回 x 的自然对数。
log10(x) 返回 x 的以 10 为底的对数。
log1p(x) 返回 1 + x 的自然对数。
log2(x) 返回 x 的以 2 为底的对数。
max(xyz, ..., n) 返回值最高的数字。
min(xyz, ..., n) 返回值最小的数字。
pow(xy) 返回 x 的 y 次幂值。
random() 返回 0 到 1 之间的随机数。
round(x) 将 x 舍入为最接近的整数。
sign(x) 返回数的符号(检查它是正数、负数还是零)。
sin(x) 返回 x 的正弦值(x 以弧度为单位)。
sinh(x) 返回 x 的双曲正弦值。
sqrt(x) 返回 x 的平方根。
tan(x) 返回角度的正切值。
tanh(x) 返回数的双曲正切值。
trunc(x) 返回数字 (x) 的整数部分。

 

常用方法:

Math.round

  • 返回值是X四舍五入为最接近的整数。
Math.round(6.8);    // 返回 7
Math.round(2.3);    // 返回 2

Math.pow

  • 返回值是x的y次幂
Math.pow(8, 2);      // 返回 64

Math.sqrt

  • 返回x的平方根
Math.sqrt(64);      // 返回 8

Math.abs

  • 返回x的绝对(正)值
Math.abs(-4.7);     // 返回 4.7

Math.min和Math.max

  • 查找参数列表中的最低或最高值
Math.min(0, 450, 35, 10, -8, -300, -78);  // 返回 -300
Math.max(0, 450, 35, 10, -8, -300, -78);  // 返回 450

Math对象访问的8个数学常量

Math.E          // 返回欧拉指数(Euler's number)
Math.PI         // 返回圆周率(PI)
Math.SQRT2      // 返回 2 的平方根
Math.SQRT1_2    // 返回 1/2 的平方根
Math.LN2        // 返回 2 的自然对数
Math.LN10       // 返回 10 的自然对数
Math.LOG2E      // 返回以 2 为底的 e 的对数(约等于 1.414)
Math.LOG10E     // 返回以 10 为底的 e 的对数(约等于 0.434)

random随机方法:

随机整数:

Math.floor(Math.random() * 10);		// 返回 0 至 9 之间的数
Math.floor(Math.random() * 11);		// 返回 0 至 10 之间的数
Math.floor(Math.random() * 100);	// 返回 0 至 99 之间的数
Math.floor(Math.random() * 101);	// 返回 0 至 100 之间的数
Math.floor(Math.random() * 10) + 1;	// 返回 1 至 10 之间的数
Math.floor(Math.random() * 100) + 1;	// 返回 1 至 100 之间的数
<body>

<h2>JavaScript Math.random()</h2>

<p>每当您点击按钮,getRndInteger(min, max) 就会返回 1 与 10(均包含)之间的随机数:</p>

<button onclick="document.getElementById('demo').innerHTML = getRndInteger(1,10)">点击我</button>

<p id="demo"></p>

<script>
function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}
</script>

</body>

 

标签:返回,10,min,floor,random,JS,随机,Math
From: https://www.cnblogs.com/xinbing/p/16969212.html

相关文章