【发布时间】:2012-11-28 20:04:26
【问题描述】:
对于我正在处理的项目,我需要一个 Javascript 函数,它会在给定范围内返回一个随机数,而不会重复自身,直到整个范围“耗尽”。由于周围没有这样的东西,我设法自己创造了它。
该函数还需要传递id。这样,如果您需要多个随机数,每个都有自己的历史记录,id 会跟踪它们。
该功能有效,但我需要一些建议;
- 这是实现我想要实现的“正确”方式吗?
-
inArray()在非常大的范围 (maxNum) 值下的执行速度有多快?我有一种感觉,大数字会减慢函数的速度,因为它会随机化数字,直到它生成一个仍然“有效”的数字(即不在历史数组中)。但我想不出另一种方法来做到这一点..
脚本:
var UniqueRandom = {
NumHistory: [],
generate: function (maxNum, id) {
if (!this.NumHistory[id]) this.NumHistory[id] = [];
if (maxNum >= 1) {
var current = Math.round(Math.random() * (maxNum - 1)), x = 0;
if (maxNum > 1 && this.NumHistory[id].length > 0) {
if (this.NumHistory[id].length !== maxNum) {
while ($.inArray(current, this.NumHistory[id]) !== -1) {
current = Math.round(Math.random() * (maxNum - 1));
x = x + 1;
}
this.NumHistory[id].push(current);
} else {
//reset
this.NumHistory[id] = [current];
}
} else {
//first time only
this.NumHistory[id].push(current);
}
return current;
} else {
return maxNum;
}
},
clear: function (id) {
this.NumHistory[id] = [];
}
};
用法是:(100 是 (0-100) 范围,the_id 是.. id)
UniqueRandom.NumHistory[100, 'the_id']
我已经设置了一个Fiddle 有一个演示。
【问题讨论】:
标签: javascript jquery random