Math.random()方法返回0-1范圍內(nèi)的浮點隨機數(shù)(包括0,但不包括1)。
Math.random();測試看看?/?
注意: Math.random()始終返回介于0和1之間的浮點數(shù)。
Math.random()與 Math.floor()一起使用可用于返回隨機整數(shù)。
本示例返回一個從0到9的隨機整數(shù):
Math.floor(Math.random() * 10);測試看看?/?
本示例返回一個從0到10的隨機整數(shù):
Math.floor(Math.random() * 11);測試看看?/?
本示例返回一個從1到10的隨機整數(shù):
Math.floor((Math.random() * 10) + 1);測試看看?/?
本示例返回一個從1到100的隨機整數(shù):
Math.floor((Math.random() * 100) + 1);測試看看?/?
此示例返回一個從11到20的隨機整數(shù):
Math.floor((Math.random() * 10) + 11);測試看看?/?
本示例返回一個從51到100的隨機整數(shù):
Math.floor((Math.random() * 50) + 51);測試看看?/?
此示例返回介于min(包括)和max(排除)之間的隨機數(shù):
function getRandom(min, max) { return Math.floor(Math.random() * (max - min)) + min; }測試看看?/?
此示例返回介于min和max之間的隨機數(shù)(均包括在內(nèi)):
function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }測試看看?/?
返回鼠標移動的隨機數(shù):
將鼠標指針移到下面的DIV上: