4 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
Mozilla Developer Network頁(yè)面上有一些示例:
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
這是它背后的邏輯。這是一個(gè)簡(jiǎn)單的三條規(guī)則:
Math.random()返回Number0(包括)和1(不包括)之間的值。所以我們有這樣的間隔:
[0 .................................... 1)
現(xiàn)在,我們想要一個(gè)介于min(包含)和max(獨(dú)家)之間的數(shù)字:
[0 .................................... 1)
[min .................................. max)
我們可以使用它Math.random來(lái)獲取[min,max]區(qū)間內(nèi)的通訊記錄。但是,首先我們應(yīng)該通過(guò)min從第二個(gè)區(qū)間減去一點(diǎn)來(lái)解決問(wèn)題:
[0 .................................... 1)
[min - min ............................ max - min)
這給出了:
[0 .................................... 1)
[0 .................................... max - min)
我們現(xiàn)在可以申請(qǐng)Math.random然后計(jì)算通訊員。我們選擇一個(gè)隨機(jī)數(shù):
Math.random()
|
[0 .................................... 1)
[0 .................................... max - min)
|
x (what we need)
所以,為了找到x,我們會(huì)做:
x = Math.random() * (max - min);
不要忘記添加min回來(lái),以便我們?cè)赱min,max]間隔中得到一個(gè)數(shù)字:
x = Math.random() * (max - min) + min;
這是MDN的第一個(gè)功能。第二個(gè),返回一個(gè)介于min和之間的整數(shù)max。
現(xiàn)在獲取整數(shù),你可以使用round,ceil或floor。
您可以使用Math.round(Math.random() * (max - min)) + min,但這會(huì)產(chǎn)生非均勻分布。這兩種,min而max只有大約一半滾動(dòng)的機(jī)會(huì):
min...min+0.5...min+1...min+1.5 ... max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round()
min min+1 max
與max從區(qū)間中排除,它有一個(gè)甚至更少的機(jī)會(huì),而不是滾動(dòng)min。
隨著Math.floor(Math.random() * (max - min +1)) + min你有一個(gè)完美均勻的分布。
min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval)
| | | | | |
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor()
min min+1 max-1 max
你不能使用ceil()和-1在那個(gè)等式中,因?yàn)閙ax現(xiàn)在滾動(dòng)的機(jī)會(huì)略少,但你也可以滾動(dòng)(不需要的)min-1結(jié)果。

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
的Math.random()
從Mozilla Developer Network文檔中:
// Returns a random integer between min (include) and max (include)
Math.floor(Math.random() * (max - min + 1)) + min;
有用的例子:
// 0 - 10
Math.floor(Math.random() * 11);
// 1 - 10
Math.floor(Math.random() * 10) + 1;
// 5 - 20
Math.floor(Math.random() * 16) + 5;
// -10 - (-2)
Math.floor(Math.random() * 9) - 10;
添加回答
舉報(bào)