如何在Meteor中生成 4位字母数字代码而不重复?
答案 0 :(得分:0)
您要求4位数字,但也要说'字母数字'。无论哪种方式:
function generate4DigitNonRepeatingNumericCode() {
ret = "";
while (ret.length < 4) {
var pickANumberBetween0and9 = ("" + Math.random()).charAt(2);
if (ret.indexOf("" + pickANumberBetween0and9) == -1)
ret += pickANumberBetween0and9;
}
return ret;
}
那个不是Meteor特定的,可以在任何JavaScript应用程序中使用。对于字母数字,我们将采用快捷方式并使用Meteor的Meteor.Collection.ObjectID
:
function generate4CharacterNonRepeatingAlphanumericCode() {
ret = "";
while (ret.length < 4) {
var pickACharacter = ("" +
new Meteor.Collection.ObjectID().toHexString()).charAt(0);
if (ret.indexOf("" + pickACharacter) == -1)
ret += pickACharacter;
}
return ret;
}