如何在流星中生成4位数的字母数字代码?

时间:2014-04-21 12:20:08

标签: javascript meteor

如何在Meteor中生成 4位字母数字代码而不重复

1 个答案:

答案 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;
}