当前位置:优学网  >  在线题库

使用javascript生成固定长度的字母数字字符串

发表时间:2022-07-25 00:49:04 阅读:66

我的应用程序中有以下代码片段,用于生成长度为9的字母数字字符串.

const makeid = () => {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const numbers = '0123456789';

  for (var i = 0; i < 9; i++) {
    if (i == 2 || i == 3 || i == 4) {
      result += characters.charAt(Math.floor(Math.random() *
        characters.length));
    } else {
      result += numbers.charAt(Math.floor(Math.random() *
        numbers.length));
    }
  }
  return result;
}

console.log(makeid());
//51ADA5532

上面的代码工作正常.给出结果大约需要200-400毫秒.

我如何优化上述代码以提高性能,或者是否有其他方法比我的方法具有性能优势?

任何建议都会有帮助.

🎖️ 优质答案
相关问题