JS中Math函数的常用方法

JavaScript015

JS中Math函数的常用方法,第1张

JS中Math函数的常用方法

Math是数学函数,但又属于对象数据类型typeof Math=>‘object’

console.dir(Math)查看Math的所有函数方法。

1,Math.abs()获取绝对值

Math.abs(-12) = 12

2,Math.ceil() and Math.floor()向上取整和向下取整

console.log(Math.ceil(12.03))//13

console.log(Math.ceil(12.92))//13

console.log(Math.floor(12.3))//12

console.log(Math.floor(12.9))//12

3,Math.round()四舍五入

注意:正数时,包含5是向上取整,负数时包含5是向下取整。

1、Math.round(-16.3) = -16

2、Math.round(-16.5) = -16

3、Math.round(-16.51) = -17

4,Math.random()取[0,1)的随机小数

案例1:获取[0,10]的随机整数

console.log(parseInt(Math.random()*10))//未包含10

console.log(parseInt(Math.random()*10+1))//包含10

案例2:获取[n,m]之间的随机整数

Math.round(Math.random()*(m-n)+n)

5,Math.max() and Max.min()获取一组数据中的最大值和最小值

console.log(Math.max(10,1,9,100,200,45,78))

console.log(Math.min(10,1,9,100,200,45,78))

6,Math.PI获取圆周率π 的值

console.log(Math.PI)

7,Math.pow() and Math.sqrt()

Math.pow()获取一个值的多少次幂

Math.sqrt()对数值开方

Math.pow(10,2) = 100

Math.sqrt(100) = 10

JavaScript中的math 对让我们能够对执行一些数学操作。它具有数学常数和函数的属性和方法。在今天的文章中将介绍 Math对象的一些有用方法。

1. Math.min()

Math.min()是 JS 数学库中的函数,用于将所有传递的值中的最小值返回给该方法。

Math.min(0, 150, 30, 20, -8, -200) // -200

2. Math.max()

Math.max()方法可返回两个指定的数中带有较大的值的那个数。

Math.max(0, 150, 30, 20, -8, -200) // 150

3. Math.round()

Math.round() 函数返回一个数字四舍五入后最接近的整数。

Math.round(4.7) // 5

Math.round(4.4) // 4

4. Math.sqrt()

Math.sqrt() 函数返回一个数的平方根,即:

Math.sqrt(64) // 8

Math.sqrt(25) // 5

5. Math.pow()

Math.pow() 函数返回基数(base)的指数(exponent)次幂,即:

Math.pow(8, 2) // 64

6. Math.floor()

Math.floor() 返回小于或等于一个给定数字的最大整数。

Math.floor(4.7) // 4

Math.floor(8.6) // 8

7. Math.random()

Math.random() 函数返回一个浮点, 伪随机数在范围从0到小于1,也就是说,从0(包括0)往上,但是不包括1(排除1),然后你可以缩放到所需的范围。实现将初始种子选择到随机数生成算法它不能被用户选择或重置。

Math.random() // 0.15497907645259867

8. Math.cos()

Math.cos() 函数返回一个数值的余弦值。

Math.cos(0, Math.PI / 180) // 1

9. Math.sin()

Math.sin() 函数返回一个数值的正弦值。

Math.sin(90 * Math.PI / 180) // 1

Math.ceil() 函数返回大于或等于一个给定数字的最小整数。

Math.ceil(4.4) // 5

总结

在执行一些数字操作时,JS Math 对象是很强大且很有用的,除了上述10个方法,Math 对象还有其它很多方法,这个留给大家自己去看文档,今天的分享就到这了,感谢大家的观看,我们下期再见。

一个Math函数,

例如:Math.pow(4,3)返回4的三次幂,

用法:Math.pow(x,y)

x必需传。底数。必须是数字。

y必需传。幂数。必须是数字。

如果结果是虚数或负数,则该方法将返回 NaN。如果由于指数过大而引起浮点溢出,则该方法将返回 Infinity