2015-04-07 72 views
0

我正常使用它。高效得到兩個間隔之間的隨機整數

var min = 0; 
var max = 1; 

console.log(Math.round((Math.random() * (max - min) + min))); 

它的工作原理罰款和花花公子,但我不能克服的思維,這可能是產生這種結果的一個昂貴的方式,沒有人知道的更有效的方法?

這是最有效的方法嗎?

+0

兩者

我不知道有什麼更好的方法,所有實現我遇到做同樣的 – holtc

+2

這傢伙似乎正在尋找同樣的事情,http://stackoverflow.com/questions/8775962/what-is-the-fastest-way-to-generate-a-random-integer-in-javascript – DasBeasto

+0

您是否使用http://jsperf.com創建了性能測試? –

回答

0

嘿,你可以試試這個方法也

Math.floor(Math.random() * max) + min 

這將有效地工作。

+1

這不起作用。你的最大值是一個範圍 –