vendredi 27 décembre 2019

Generate random password based on user input in Javascript

The assignment is to prompt for length of the password and character type from the user, then generate a random password. I think the for loop isn't working correctly. The retVal is returned empty because the for loop isn't passing it anything. I tried removing the charAt function and having the Math.floor give me just and index, that just gave me undefinedundefinedundefinedundefinedundefinedundefined. Back with the regular charAt function I'm getting nothing.

var length = prompt("How many characters will your password be? Enter a number between 8 and 128");

//ask for character type
var charType = prompt("Enter a character type: special, numeric, uppercase, lowercase.");

//generate password
function generatePassword() {
  //evaluate character type
  var charSet = "";
  if( charType.toLowerCase === "lowercase" ) {
    charSet = "abcdefghijklmnopqrstuvwxyz";
  } else if( charType.toLowerCase === "uppercase" ) {
    charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  } else if( charType.toLowerCase === "numeric" ) {
    charSet = "0123456789";
  } else if( charType.toLowerCase === "special" ) {
    charSet = " !\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~";
  } 
  //return value
  var retVal = "";
  //for (var i = 0, n = charSet.length; i < length; i++) {
    for (var i = 0, n = length; i < length; i++) {
    //picks a character within charSet at index of random number
    retVal += charSet.charAt(Math.floor(Math.random() * n));
  }
  console.log(retVal);
  return retVal;
}```



Aucun commentaire:

Enregistrer un commentaire