JavaScript 随机
Math.random()
Math.random() 返回 0(包括) 至 1(不包括) 之间的随机数:
<!DOCTYPE html><html><body><h2>JavaScript Math.random()</h2><p>Math.random() 返回 0(包含)和 1(不包括)之间的随机数:</p><p id="demo"><script>document.getElementById("demo").innerHTML = Math.random();</script></body></html>
Math.random() 总是返回小于 1 的数。
JavaScript 随机整数
Math.random() 与 Math.floor() 一起使用用于返回随机整数。
<!DOCTYPE html><html><body><h2>JavaScript Math</h2><p>Math.floor(Math.random() * 10) 返回 0 与 9 之间的随机整数(均包含):</p><p id="demo"><script>document.getElementById("demo").innerHTML =Math.floor(Math.random() * 10);</script></body></html>
实例
<!DOCTYPE html><html><body><h2>JavaScript Math</h2><p>Math.floor(Math.random() * 11) 返回 0 与 10 之间的随机整数(均包含):</p><p id="demo"><script>document.getElementById("demo").innerHTML =Math.floor(Math.random() * 11);</script></body></html>
实例
<!DOCTYPE html><html><body><h2>JavaScript Math</h2><p>Math.floor(Math.random() * 100)) 返回 0 与 99 之间的随机整数(均包含):</p><p id="demo"><script>document.getElementById("demo").innerHTML =Math.floor(Math.random() * 100);</script></body></html>
实例
<!DOCTYPE html><html><body><h2>JavaScript Math</h2><p>Math.floor() 与 Math.random() * 101 一起使用,返回 0 与 100 之间的随机整数(均包含):</p><p id="demo"><script>document.getElementById("demo").innerHTML =Math.floor(Math.random() * 101);</script></body></html>
实例
<!DOCTYPE html><html><body><h2>JavaScript Math</h2><p>Math.floor(Math.random() * 10) + 1) 返回 1 与 10 之间的随机整数(均包含):</p><p id="demo"><script>document.getElementById("demo").innerHTML =Math.floor(Math.random() * 10) + 1;</script></body></html>
实例
<!DOCTYPE html><html><body><h2>JavaScript Math</h2><p>Math.floor(Math.random() * 100) + 1) 返回 1 与 100 之间的随机整数(均包含):</p><p id="demo"><script>document.getElementById("demo").innerHTML =Math.floor(Math.random() * 100) + 1;</script></body></html>
一个适当的随机函数
正如你从上面的例子看到的,创建一个随机函数用于生成所有随机整数是一个好方法。
这个 JavaScript 函数始终返回介于 min(包括)和 max(不包括)之间的随机数:
<!DOCTYPE html><html><body><h2>JavaScript Math.random()</h2><p>每当您点击按钮,getRndInteger(min, max) 就会返回 0 与 9(均包含)之间的随机数:</p><button onclick="document.getElementById('demo').innerHTML = getRndInteger(0,10)">点击我</button><p id="demo"><script>function getRndInteger(min, max) {return Math.floor(Math.random() * (max - min)) + min;}</script></body></html>
这个 JavaScript 函数始终返回介于 min 和 max(都包括)之间的随机数:
<!DOCTYPE html><html><body><h2>JavaScript Math.random()</h2><p>每当您点击按钮,getRndInteger(min, max) 就会返回 1 与 10(均包含)之间的随机数:</p><button onclick="document.getElementById('demo').innerHTML = getRndInteger(1,10)">点击我</button><p id="demo"><script>function getRndInteger(min, max) {return Math.floor(Math.random() * (max - min + 1) ) + min;}</script></body></html>