JavaScript random() 方法
實例
返回介於 0(包含) ~ 1(不包含) 之間的一個亂數:
Math.random();
輸出結果:
定義和用法
random() 方法可返回介於 0(包含) ~ 1(不包含) 之間的一個亂數。
流覽器支持
所有主要流覽器都支持 random() 方法
語法
Math.random()
返回值
類型 | 描述 |
---|---|
Number | 0.0 ~ 1.0(不包含) 之間的一個偽亂數。 |
技術細節
JavaScript 版本: | 1.0 |
---|
更多實例
實例
在本例中,我們將取得介於 1 到 10 之間的一個亂數:
Math.floor((Math.random()*10)+1);
輸出結果:
實例
在本例中,我們將取得介於 1 到 100 之間的一個亂數:
Math.floor((Math.random()*100)+1);
輸出結果:
實例
以下函數返回 min(包含)~ max(不包含)之間的數字:
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
實例
以下函數返回 min(包含)~ max(包含)之間的數字:
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}