栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

生成(0-X)范围内的唯一编号,并保留历史记录以防止重复

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

生成(0-X)范围内的唯一编号,并保留历史记录以防止重复

我写了这个功能。它使用生成的数字的历史记录保留其自己的数组,防止初始重复,如果范围内的所有数字均已输出一次,则继续输出随机数:

// Generates a unique number from a range// keeps track of generated numbers in a history array// if all numbers in the range have been returned once, keep outputting random numbers within the rangevar UniqueRandom = { NumHistory: new Array(), generate: function(maxNum) {        var current = Math.round(Math.random()*(maxNum-1));        if (maxNum > 1 && this.NumHistory.length > 0) { if (this.NumHistory.length != maxNum) {     while($.inArray(current, this.NumHistory) != -1) { current = Math.round(Math.random()*(maxNum-1)); }     this.NumHistory.push(current);     return current; } else {     //unique numbers done, continue outputting random numbers, or we could reset the history array (NumHistory = [];)     return current; }        } else { //first time only this.NumHistory.push(current); return current;        }    }};

我希望这对某人有用!

编辑:正如下面的Pointy所指出的,它在大范围内可能会变慢,在0-1000的范围内运行,似乎运行良好)。然而我并不需要很大的范围,所以如果您希望生成并跟踪很大的范围,则此功能可能确实不适合。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/420752.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号