JavaScript Math()使用技巧
1、案例一:两数比大小。我们要用JavaScript Math()对于两数进行比大小,把小的写在网页上面。
2、整个代码的浯裁佻辞流程如下所示:所有的小的数字就显示在网页上了。<html><body><script type="text/jav锾攒揉敫ascript">document.write(Math.min(1,2) + "<br />")document.write(Math.min(-1,3) + "<br />")document.write(Math.min(-5,-7) + "<br />")document.write(Math.min(7.22,7.30))</script></body></html>
3、我们如果把min 改成 max 则结果就完全不同了。<html><body><script type="text/javascript">document.write(Math.max(1,2) + "<br />")document.write(Math.max(-1,3) + "<br />")document.write(Math.max(-5,-7) + "<br />")document.write(Math.max(7.22,7.30))</script></body></html>
4、一个随机数字的案例。每一次的点击,这个网页上的数字都不一样。<html><body><script type="text/javascript">document.write(Math.random())</script></body></html>
5、我们聪艄料姹再来看一批不同算法的案例。这里有2的平方根、圆周率、常数等等。<html><body><script type="text/javascript媪青怍牙">document.write(Math.SQRT2 + "<br />")document.write(Math.PI + "<br />")document.write(Math.E + "<br />")document.write(Math.SQRT1_2 + "<br />")document.write(Math.LN2)</script></body></html>
6、这是一个把两种算法用在一起的代码流程。每一次有结果都不一样!<html><body><script type="text/javascript">document.write(Math.floor(Math.random()*11))</script></body></html>