【问题标题】:How to generate 4 digits alphanumeric code in meteor? [closed]如何在流星中生成 4 位字母数字代码? [关闭]
【发布时间】:2014-04-22 03:09:44
【问题描述】:

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

【问题讨论】:

  • 因为你可以添加 npm 支持。为什么不使用 hashids 这样的库?

标签: javascript meteor


【解决方案1】:

您要求 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;
}

【讨论】:

    猜你喜欢
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多