在JavaScript中生成包含字母数字字符的密码

问题描述

我想生成一个带有Alpha数字字符的随机密码。我编写了一个函数,该函数返回带有字母数字字符的随机密码。但是我只想从提供的字符串中添加4个字母数字字符。 已编辑:我知道这不是最好的解决方案,但是我已经设法获得了期望的输出,如果有人希望获得有关代码的帮助并对其进行优化,那将非常有帮助。

function getRandomPassword(length,numberOfNonAlphaNumericChars) {
const passwordDigit = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMnop1234567890";
const alphaNumericChar = "!@#$%^&*()_-+=[{]};:>|./?";
var temp1 = "";
var temp2 = "";
var pass = "";
if(length < 1 || length > 128) {
console.log("Number Exceeds");
}
if(numberOfNonAlphaNumericChars > length || numberOfNonAlphaNumericChars < 0) {
console.log("Error");
}
  for(var i = 0; i < length; i++) {
        var x = Math.floor(Math.random() * length);
    temp1 += passwordDigit.charat(x);
    }
  for(var j = 0; j < numberOfNonAlphaNumericChars; j++) {
    var alphaNumericCharPos = Math.floor(Math.random() * numberOfNonAlphaNumericChars);
    temp2 += alphaNumericChar.charat(alphaNumericCharPos);
  }
    
  var newPass = [temp1.slice(0,x),temp2,temp1.slice(x)].join('');
    
  console.log(newPass);
  return newPass;
}
getRandomPassword(16,4);

jsfiddle:(https://jsfiddle.net/37rjgfad/11/

解决方法

这将为您提供4个字母数字字符:

function jumble(str) {
  return [...str]
    .sort(() => Math.random() - 0.5)
    .join('')
}

// no change to this function
function randomString(length,chars) {
    var mask = '';
    if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
    if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    if (chars.indexOf('#') > -1) mask += '0123456789';
    if (chars.indexOf('!') > -1) mask += '!@#$%^&*()_-+=[{]};:>|./?';
    var result = '';
    for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
    return result;
}

console.log(
  jumble(randomString(12,'aA#') + randomString(4,'!'))
)

如果需要其他发行版,请根据需要进行修改。例如:

jumble(
  randomString(4,'a')
  + randomString(4,'A')
  + randomString(4,'!')
  + randomString(4,'#')
)

将为您提供16个字符的字符串,其中每个字符类型恰好包含4个字符,或者:

jumble(randomString(12,'!') + randomString(4,'aA#'))

将为您提供12个非字母数字和4个字母数字。

,

您可以将用于选择字符的字母数字字符串减少到仅4个字符。

function randomString(length,chars) {
  var mask = '',result = '';
  if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
  if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  if (chars.indexOf('#') > -1) mask += '0123456789';
  for(var i = 0; i < 4; i++) {
    result += mask[Math.floor(Math.random() * mask.length)];
  }
  mask = '';
  if (chars.indexOf('!') > -1) {
    mask += '!@#$%^&*()_-+=[{]};:>|./?';
  }
  for (var i = 0; i < length - 4; i++) {
    result += mask[Math.floor(Math.random() * mask.length)];
  }
  return result;
}

console.log(randomString(16,'aA#!'));
console.log(randomString(16,'#aA'));
console.log(randomString(16,'#A!'));

对函数的第二次调用在前4个字符之后返回未定义的结果,因为密码限制为4个字母数字字符,并且不允许使用符号。

请注意,通过调用document.write(),您首先要擦除文档,然后附加新文本。您将只能看到您上次写的文字。因此,我使用了console.log()