【发布时间】:2014-11-17 01:30:42
【问题描述】:
我正在开发一个在随机时间后替换图像的系统。但是,我目前让它在数字 1-5 之间进行选择以用于显示目的。我想知道是否可以使用 Math.random() 使某些数字比其他数字更稀有。例如,如果我希望数字 1 经常出现,但希望数字 5 非常罕见,我可以使用 Math.random() 来做到这一点吗?如果不是,那有什么办法呢?
我目前拥有的代码:
$(function() {
$("#test").click(function() {
randomGen();
});
function randomGen() {
var rand = Math.floor((Math.random() * 5) + 1);
var test = Math.floor((Math.random() * 15000) + 1);
if (rand === 1) {
console.log(rand);
}
if (rand === 2) {
console.log(rand);
}
if (rand === 3) {
console.log(rand);
}
if (rand === 4) {
console.log(rand);
}
if (rand === 5) {
console.log(rand);
}
setTimeout(randomGen, test);
}
});
【问题讨论】: