1. Computing

Password Generator Tutorial

Page Five

Join the Discussion

Questions? Comments?

<< Previous Page

var y = charSet.length;
while (i < len-1) {
chars[i++] = charSet.charAt(Math.floor(Math.random()*y));
}

Having made sure that our array contains one of each of the required character types we now select further characters for our password from the complete set of characters in all of the selected groups. Since there are a number of possible lengths that the valid charSet can contain I use the length method to determine how many they are but I only do this once and assign the length to a variable since accessing a variable is more efficient than accessing a method. The while loop will add sufficient characters to the array to bring the total length up to one less than we specified that we wanted (because we still have to deal with generating the first character separately).

chars.sort(randOrd);

We now have sufficient characters in the array for all of the password except the first character. Because we first made sure that each of the required character types was represented in the array by adding them first, those characters appear in specific positions. This isn't what we wanted. If we want the password to contain a number (for example) we don't necessarily have to have a number in the second position of the password. We therefore use the sort method with the randomiser function to sort the entries currently in the array into a random order. It is so that this step could be performed that I used an array rather than a character string to store the characters for the password in the first place.

©2014 About.com. All rights reserved.