Math 对象
Math对象提供了大量有效的数学函数和数值操作方法。
Math对象有点与众不同,因为Javascript会自动创建它,在使用Math对象之前,不需要将变量声明为Math对象,也不需要定义新的Math对象,所以Math对象用起来很容易。
var value=Math.PI*15*15;
document.write(value); //输出一个圆的面积
Math 对象的方法
abs() 方法
返回数的绝对值。
document.write(Math.abs(-7.25)) // 输出 7.25
min() 和 max() 方法 ———— 查找最大值和最小值
有两个数字,要确定哪个较大,哪个较小,为此,Math对象提供了min() 和 max() 方法。
document.write(Math.max(-3,-5) + "<br />")// -3 document.write(Math.min(-3,-5) + "<br />")// -5
舍入方法
Math对象提供了几个数字舍入方法,每个方法都有各自的用途。
ceil() 方法
ceile() 方法总是把数值向上取整,
document.write(Math.ceil(5.1) + "<br />") //输出 6 document.write(Math.ceil(-5.1) + "<br />") // 输出 -5
floor() 方法
floor()方法 可对一个数进行向下取整。
document.write(Math.floor(5.1) + "<br />") //输出 5 document.write(Math.floor(-5.1) + "<br />") //输出 -6
round() 方法
数学中的四舍五入,当小数部分大于等于0.5是向上,小于0.5时向下。
document.write(Math.round(45.5) ) // 输出 46 document.write(Math.round(45.49) ) //输出 45
Math.round、parseInt、Math.floor和Math.ceil小数取整总结
random() 方法
random() 方法可返回介于 0 ~ 1 之间的一个随机数。
var count ; for( var i=0;i< 6;i++){ count =(Math.floor(Math.random()*6)+1); document.write(count + "<br/>") }
上述代码中,使用random方法返回一个0~1(不包含1)之间的随机浮点数,把这个数乘以6 ,就得到一个0~6之间(不包含6) 的随机数,然后加1 ,就得到一个1~7的(不包含7的)的随机数,接着用floor()方法向下修整,便得到了一个1~6(包含6)的随机数,这就是摇骰子代码的一个小游戏,可以多 完善,来更有趣。
pow() 方法
pow() 方法可返回 x 的 y 次幂的值。
document.write(Math.pow(2,4) ) // 输出 16 document.write(Math.pow(-2,4) ) // 输出 16
Math方法还有一些方法再次不再赘述,有兴趣的可以参考W3C
的文档进行查阅!
转载请标明出处!!!!