JavaScript Math(算数)对象

JavaScript Math对象详解
本文介绍了JavaScript中的Math对象及其常用方法,如round()、random()、max()和min()等,并通过示例展示了如何使用这些方法执行基本的数学运算。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值