本文介绍 JavaScript 中 Math.random() 方法的用法。该方法用于生成介于 0(包含)和 1(不包含)之间的伪随机浮点数。文章提供了具体的代码示例,展示了如何在 HTML 页面中调用此方法并输出随机结果,适用于需要简单随机数生成的 Web 开发场景。
Math.random() 方法概述
Math.random() 方法用于生成一个伪随机浮点数,其取值范围包含 0 但不包含 1,即区间为 [0, 1)。
Math.random() ;
该方法不接受任何参数。
- 无需参数。
返回值类型为 Number。
- 返回一个介于 0(含)和 1(不含)之间的随机浮点数。
代码示例与结果
以下示例演示了如何在 JavaScript 中调用 Math.random() 并输出结果。
<html>
<head>
<title>JavaScript Math random() Method</title>
</head>
<body>
<script type="text/javascript">
var value = Math.random( );
document.write("First Test Value : " + value );
var value = Math.random( );
document.write("<br />Second Test Value : " + value );
var value = Math.random( );
document.write("<br />Third Test Value : " + value );
var value = Math.random( );
document.write("<br />Fourth Test Value : " + value );
</script>
</body>
</html>
执行上述代码后,控制台或页面将显示多次生成的随机数值,每次运行结果均不同。
First Test Value : 0.28182050319352636
Second Test Value : 0.6375786089661319
Third Test Value : 0.6780129774072902
Fourth Test Value : 0.7310958163154001