JavaScript Math()使用技巧

2025-11-03 02:25:32

1、案例一:两数比大小。我们要用JavaScript Math()对于两数进行比大小,把小的写在网页上面。

JavaScript Math()使用技巧

2、整个代码的流程如下所示:所有的小的数字就显示在网页上了。

<html>

<body>

<script type="text/javascript">

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>

JavaScript Math()使用技巧

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>

JavaScript Math()使用技巧

4、一个随机数字的案例。每一次的点击,这个网页上的数字都不一样。

<html>

<body>

<script type="text/javascript">

document.write(Math.random())

</script>

</body>

</html>

JavaScript Math()使用技巧

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>

JavaScript Math()使用技巧

6、这是一个把两种算法用在一起的代码流程。每一次有结果都不一样!

<html>

<body>

<script type="text/javascript">

document.write(Math.floor(Math.random()*11)) 

</script>

</body>

</html>

JavaScript Math()使用技巧

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
相关推荐
  • 阅读量:78
  • 阅读量:148
  • 阅读量:134
  • 阅读量:48
  • 阅读量:160
  • 猜你喜欢