Math(算数对象)的作用是执行常见的算数任务。
实例:
round()的使用:
<script type="text/javascript">
document.write(Math.round(0.60) + "<br />")
document.write(Math.round(0.50) + "<br />")
document.write(Math.round(0.49) + "<br />")
document.write(Math.round(-4.40) + "<br />")
document.write(Math.round(-4.60))
</script>
结果:
1
1
0
-4
-5
使用random()返回0到1之间的随机数
document.write(Math.random())
使用max()返回两个给定的数中较大的数
document.write(Math.max(5,7) + "<br />")
同理使用min()返回两个给定的数中较小的数
Math对象提供多种算数值类型和函数,无需在使用这个对象前对其进行定义
算数值
JavaScript提供8种可被Math对象访问的算数值:
常数 Math.E
圆周率 Math.PI
2的平方根 Math.SQRT2
1/2的平方根 Math.SQRT1_2
2的自然对数 Math.LN2
10的自然对数 Math.LN10
以2为底e的对数 Math.LOG2E
以10为底e的对数 Math.LOG10E
算数方法
除了可被Math对象访问的算数值以外,还有几个函数(方法)可以使用
使用 Math 对象的 round 方法对一个数进行四舍五入
使用 Math 对象的 random() 方法来返回一个介于 0 和 1 之间的随机数
使用 Math 对象的 floor() 方法和 random() 来返回一个介于 0 和 10 之间的随机数
Math.floor(Math.random()*11)