DIV CSS 佈局教程網

Math.random() 隨機數函數用法與取得指定範圍的公式
編輯:JavaScript基礎知識     

語法

Math.random();

參數

無參數。

回傳值

回傳 0 與 1 之間的偽隨機數,可能等於 0,但恆小於 1,也就是範圍 [0, 1)。

基本示例

document.write(Math.random());

取得指定範圍

document.write(Math.random() * (20 - 10) + 10);   // 10 到 20 之間
document.write(Math.random() * (n - m) + m);        // m 到 n 之間

通用公式為 Math.random() * (max - min) + min,得到的是浮點數。若需要整數,再往外包一層 Math.floor():

function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

這裡的 + 1 是為了讓最大值也能被取到;若你的需求是「不含最大值」,則可省略。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved