JavaScript Math(算数)对象

来源:互联网 发布:最好用的手机编程软件 编辑:程序博客网 时间:2024/04/28 15:46

Math(算数)对象的作用是:执行常见的算数任务。

实例

round()  (四舍五入)
如何使用 round()。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title></head><body><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></body></html>
效果图:


random()
如何使用 random() 来返回 0 到 1 之间的随机数。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title></head><body><script type="text/javascript">document.write(Math.random())</script></body></html>
效果图:



max()
如何使用 max() 来返回两个给定的数中的较大的数。(在 ECMASCript v3 之前,该方法只有两个参数。)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title></head><body><script type="text/javascript">document.write(Math.max(4,6) + "<br />")document.write(Math.max(-10,1) + "<br />")document.write(Math.max(-22,-52) + "<br />")document.write(Math.max(7.25,7.30))</script></body></html>
效果图:

min()
如何使用 min() 来返回两个给定的数中的较小的数。(在 ECMASCript v3 之前,该方法只有两个参数。)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title></head><body><script type="text/javascript">document.write(Math.min(4,6) + "<br />")document.write(Math.min(-10,1) + "<br />")document.write(Math.min(-22,-52) + "<br />")document.write(Math.min(7.25,7.30))</script></body></html>
效果图:

Math 对象

Math(算数)对象的作用是:执行普通的算数任务。

Math 对象提供多种算数值类型和函数。无需在使用这个对象之前对它进行定义。

算数值

JavaScript 提供 8 种可被 Math 对象访问的算数值:

  • 常数
  • 圆周率
  • 2 的平方根
  • 1/2 的平方根
  • 2 的自然对数
  • 10 的自然对数
  • 以 2 为底的 e 的对数
  • 以 10 为底的 e 的对数

这是在 Javascript 中使用这些值的方法:(与上面的算数值一一对应)

  • Math.E
  • Math.PI
  • Math.SQRT2
  • Math.SQRT1_2
  • Math.LN2
  • Math.LN10
  • Math.LOG2E
  • Math.LOG10E

0 0