在JavaScript中,我們可以使用Math對象的random()方法返回0~1之間的一個隨機數。
語法:
Math.random()
說明:
random()方法是沒有參數的,直接調用即可。random()方法返回值是0~1之間的一個偽隨機數。
舉例:
在線測試
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
document.write("第1個隨機數是:" + Math.random() + "<br/>");
document.write("第2個隨機數是:" + Math.random() + "<br/>");
document.write("第3個隨機數是:" + Math.random());
</script>
</head>
<body>
</body>
</html>
在浏覽器預覽效果如下:
分析:
由於random()方法產生的數是隨機生成的, 網友們自己測試的結果有可能跟上面結果不一樣。
隨機數非常有用,其中驗證碼就可以使用random()方法實現。有機會我們再給大家分享一下具體實現方法。