Math(算数)对象的作用是:执行常见的算数任务。
实例
<!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>
效果图:
<!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()
<!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()
<!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