Home > Enterprise >  string random characters in a for loop
string random characters in a for loop

Time:10-09

Im having trouble with the following code while trying to make a random password generator. The first two lines seem to be working as intended. I confirmed this with the following:

If I replace the "passwordText = passwordText.concat(character:" with "console.log(character)" it works in the console. Picks a random char from an array and will console log it the desired amount of times.

However, on line 3 I'm trying to concat these random chars into one string. Any ideas? I'm getting a TypeError: Cannot read property 'concat'. All variables are declared.

for (var i = 0; i < inputLength; i  ) {
  character = finalCriteria[Math.floor(Math.random() * finalCriteria.length)];
  passwordText = passwordText.concat(character);
}

passwordText = passwordText.concat(character);

I would appreciate any guidance on this. Many thanks, Steven.

PS. This is my first week with JS, go easy on me! :)

CodePudding user response:

strings don't have a concat method unlike arrays. What you need is =:

  passwordText  = character;

Edit: concat not push

CodePudding user response:

Thanks everyone for your help. Below worked. I also give password text a value as mentioned by caTS.

// function to return the password 
function generatePassword() {
  for (var i = 0; i < charLength; i  ) {
    passwordText  = finalCriteria[Math.floor(Math.random() * finalCriteria.length)];
  } return passwordText  
}
  • Related