JavaScript中国的基本数值运算符可以用来进行一些简单的数学计算,而使用Math对象可以进行更高级的数学计算。与其他对象不同的是,Math对象不需要new关键字创建对象实例。
常用方法:
(1)Math.abs(number)
返回number的绝对值
<body>
<script type="text/javascript">
var num = -1;
var absNum = Math.abs(num);
alert(num + "的绝对值是:" + absNum);
</script>
</body>
(2)Math.ceil(number)
向上取整,Math.ceil(12.1) = 13;
<body>
<script type="text/javascript">
alert(Math.ceil(1.2));
</script>
</body>
(3)Math.floor(number)
向下取整,Math.floor(12.8) = 12;
<body>
<script type="text/javascript">
alert(Math.ceil(1.2));
</script>
</body>
(4)Math.max(number1, number2)
返回number1、number2中较大的值
<body>
<script type="text/javascript">
alert(Math.max(1, 2));
</script>
</body>
(5)Math.max(number1, number2)
返回number1、number2中较小的值
<body>
<script type="text/javascript">
alert(Math.min(1, 2));
</script>
</body>
(6)Math.pow(x, y);
返回x的y次幂
<body>
<script type="text/javascript">
alert(Math.pow(2, 3));
</script>
</body>
(7)Math.random()
返回0~1之间的随机数,范围为[0, 1)(即大于等于0,小于1)。
<body>
<script type="text/javascript">
alert(Math.random());
</script>
</body>
(8)Math.round(number)
返回最接近number的整数
<body>
<script type="text/javascript">
alert(Math.round(1.5);
</script>
</body>
(9)Math.sqrt(number)
返回number的正平方根
<body>
<script type="text/javascript">
alert(Math.sqrt(2));
</script>
</body>