JavaScript Math对象
Math对象用于执行数学任务。
Math对象并不是对象类,因此没有构造函数。
对象属性
| 属性 | 描述 |
| E | 返回算术常量e,即自然对数的底数(约等于2.718)。 |
| LN2 | 返回2的自然对数(约等于0.693)。 |
| LN10 | 返回10的自然对数(约等于2.302)。 |
| LOG2E | 返回以2为底的e的对数(约等于1.414)。 |
| LOG10E | 返回以10为底的e的对数(约等于0.434)。 |
| PI | 返回圆周率(约等于3.14159)。 |
| SQRT1_2 | 返回2的平方根的倒数(约等于0.707)。 |
| SQRT2 | 返回2的平方根(约等于1.414)。 |
对象方法
| 方法 | 描述 |
| abs() | 返回绝对值。 |
| acos() | 返回反余弦值。 |
| asin() | 返回反正弦值。 |
| atan() | 以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值。 |
| atan2() | 返回从 x 轴到点 (x,y) 的角度(介于 -PI/2 与 PI/2 弧度之间)。 |
| ceil() | 对数进行上舍入。 |
| cos() | 返回数的余弦。 |
| exp() | 返回 Ex 的指数。 |
| floor() | 对 x 进行下舍入。 |
| log() | 返回数的自然对数(底为e)。 |
| max() | 返回最高值。 |
| min() | 返回最低值。 |
| pow() | 返回 x 的 y 次幂。 |
| random() | 返回 0 ~ 1 之间的随机数。 |
| round() | 把数四舍五入为最接近的整数。 |
| sin() | 返回数的正弦。 |
| sqrt() | 返回数的平方根。 |
| tan() | 返回角的正切。 |
测试代码
//函数abs(x)取数的绝对值, x需要为数字或数字型的字符串。
document.write('<p>' + 'Math.abs(-253.66) = ' + Math.abs(-253.66) + '</p>');
document.write('<p>' + 'Math.abs("-253.66") = ' + Math.abs('-253.66') + '</p>');
document.write('<p>' + 'Math.abs("25abcd") = ' + Math.abs('25abcd') + '</p>');
//函数ceil(x)向上舍入到整数。
document.write('<p>' + 'Math.ceil(-253.00001) = ' + Math.ceil(-253.00001) + '</p>');
document.write('<p>' + 'Math.ceil(253.00001) = ' + Math.ceil(253.00001) + '</p>');
document.write('<p>' + 'Math.ceil(253) = ' + Math.ceil(253) + '</p>');
//函数floor(x)向下舍入到整数。
document.write('<p>' + 'Math.floor(-253.00001) = ' + Math.floor(-253.00001) + '</p>');
document.write('<p>' + 'Math.floor(253.00001) = ' + Math.floor(253.00001) + '</p>');
document.write('<p>' + 'Math.floor(253) = ' + Math.floor(253) + '</p>');
//函数round(x)四舍五入到整数。
document.write('<p>' + 'Math.round(3.499) = ' + Math.round(3.499) + '</p>');
document.write('<p>' + 'Math.round(3.501) = ' + Math.round(3.501) + '</p>');
//函数pow(x, y), 返回x的y次幂。 x是底数,y是幂数。
document.write('<p>' + 'Math.pow(2, 10) = ' + Math.pow(2, 10) + '</p>');
document.write('<p>' + 'Math.pow(1.25, 10) = ' + Math.pow(1.25, 10) + '</p>');
document.write('<p>' + 'Math.pow(2, 9.5) = ' + Math.pow(2, 9.5) + '</p>');
document.write('<p>' + 'Math.pow(2, -10) = ' + Math.pow(2, -10) + '</p>');
//函数random(),返回一个介于0(包含) 至 1(不包含)之间的伪随机数。
document.write('<p>' + 'Math.random() = ' + Math.random() + '</p>');
总结整理
- 函数abs的参数必须为数字,否则返回NaN。参数也可以是数字字符串,返回结果总是为Number。
本文介绍了JavaScript中的Math对象,包括其属性如E、PI等数学常数,以及常用的方法如abs()、ceil()、pow()等,并通过实例展示了如何使用这些方法进行数学运算。
123

被折叠的 条评论
为什么被折叠?



