Password Generator Tutorial
Page Four
Join the Discussion
More of This Feature
chars[i++] = numChars.charAt(Math.floor(Math.random()*10));
charSet += numChars;
}
With validation of the input complete we now move on to actually generating the password. I decided to start by adding a number to the array if the password is required to contain numbers. I also add the string of numbers to the set of valid characters so that once one character of each required type has been selected that the remainder of the password can be selected from all of the characters that we have defined as valid for our password contents.
Math.random generates a random number between 0 and 1. Multiplying it by 10 gives us a random number between 0 and 10. Using Math.Floor on this gives us an integer value between 0 and 9 and we then use the charAt method on our number string to retrieve the character in that position in the string (in our number string this value is the same as the position but since we need the number string for other calculations I decided to code it this way to be consistant).
The value of i is incremented after the selected character is added to the current array position so that the next entry can be added after this one. Using the push array method would have had the same effect on adding the entry to the array but we will need to have i set appropriately later in order to add the correct number of array entries to make up our password.
chars[i++] = lowerChars.charAt(Math.floor(Math.random()*26));
charSet += lowerChars;
}
if (fuc) {
chars[i++] = upperChars.charAt(Math.floor(Math.random()*26));
charSet += upperChars;
}
if (foc) {
chars[i++] = otherChars.charAt(Math.floor(Math.random()*25));
charSet += otherChars;
}
This code performs similar to the last piece of code to add a lowercase character, uppercase character, and/or other character to the array if our password is required to have them. The appropriate characters are also added to charset. In each case I have hard coded the number of characters in the appropriate string rather than using the length method to retrieve it as the lengths of the individual character strings will not change and using a constant is more efficient than a method call.

