开门必读
math和其他对象不同,math对象是一个静态对象,而不是构造函数。实际上,math只是一个由javascript设置的对象命名空间,用于存储数学函数
属性
math.e 自然对数的底数,即常量e的值(约等于2.718)
math.pi 派的值(约等于3.14159)
console.log(math.e);//2.718281828459045
console.log(math.pi);//3.141592653589793
math.ln2 2的自然对数(约等于0.693)
math.ln10 10的自然对数(约等于2.302)
math.log2e 以2为底e的对数(约等于1.414)
math.log10e 以10为底e的对数(约等于0.434)
console.log(math.ln2);//0.6931471805599453
console.log(math.ln10);//2.302585092994046
console.log(math.log2e);//1.4426950408889634
console.log(math.log10e);//0.4342944819032518
math.sqrt2 2的平方根(约等于1.414)
math.sqrt1_2 1/2的平方根,即2的平方根的倒数(约等于0.707)
console.log(math.sqrt2);//1.4142135623730951
console.log(math.sqrt1_2);//0.7071067811865476
方法
这些方法都涉及到number()隐式类型转换;若超出方法范围,将返回nan
math.min() 返回一组数字中的最小值
math.max() 返回一组数字中的最大值
console.log(math.min(1,2,3));//1
console.log(math.max(1,2,3));//3
math.ceil(num) 向上舍入为整数
math.floor(num) 向下舍入为整数
math.round(num) 四舍五入为整数
console.log(math.ceil(12.6));//13
console.log(math.floor(12.6));//12
console.log(math.round(12.6));//13
math.abs(num) 返回num的绝对值
math.random() 返回大于等于0小于1的一个随机数
console.log(math.abs(-10));//10
console.log(math.random());//0.741887615993619
math.exp(num) 返回math.e的num次幂
math.log(num) 返回num的自然对数
math.sqrt(num) 返回num的平方根(x必须是大于等于0的数)
math.pow(num,power) 返回num的power次幂
console.log(math.exp(0));//1
console.log(math.log(10));//2.302585092994046
console.log(math.sqrt(100));//10
console.log(math.pow(10,2));//100
math.sin(x) 返回x的正弦值
math.cos(x) 返回x的余弦值
math.tan(x) 返回x的正切值
math.asin(x) 返回x的反正弦值(x必须是-1到1之间的数)
math.acos(x) 返回x的反余弦值(x必须是-1到1之间的数)
math.atan(x) 返回x的反正切值
math.atan2(y,x) 返回y/x的反正切值
console.log(math.sin(30*math.pi/180));//0.49999999999999994
console.log(math.cos(60*math.pi/180));//0.5000000000000001
console.log(math.tan(45*math.pi/180));//0.9999999999999999
console.log(math.asin(1)*180/math.pi);//90
console.log(math.acos(1)*180/math.pi);//0
console.log(math.atan(1)*180/math.pi);//45
console.log(math.atan2(1,1)*180/math.pi);//45
tips
[tips1]找到数组中的最大或最小值
var values = [1,2,3,4,5,6,7,8];var max = math.max.apply(math,values);//8
[tips2]从某个整数范围内随机选择一个值
value = math.floor(math.random()*可能值的总数 + 第一个可能的值)
[tips3]通过最小值和最大值随机选择一个值
function selectfrom(lowervalue,uppervalue){var choices = uppervalue - lowervalue + 1;return math.floor(math.random()*choices + lowervalue);}var num = selectfrom(2,10);console.log(num);
math 对象方法
方法 描述
abs(x) 返回数的绝对值。
acos(x) 返回数的反余弦值。
asin(x) 返回数的反正弦值。
atan(x) 以介于 -pi/2 与 pi/2 弧度之间的数值来返回 x 的反正切值。
atan2(y,x) 返回从 x 轴到点 (x,y) 的角度(介于 -pi/2 与 pi/2 弧度之间)。
ceil(x) 对数进行上舍入。
cos(x) 返回数的余弦。
exp(x) 返回 e 的指数。
floor(x) 对数进行下舍入。
log(x) 返回数的自然对数(底为e)。
max(x,y) 返回 x 和 y 中的最高值。
min(x,y) 返回 x 和 y 中的最低值。
pow(x,y) 返回 x 的 y 次幂。
random() 返回 0 ~ 1 之间的随机数。
round(x) 把数四舍五入为最接近的整数。
sin(x) 返回数的正弦。
sqrt(x) 返回数的平方根。
tan(x) 返回角的正切。
tosource() 返回该对象的源代码。
valueof() 返回 math 对象的原始值。